如何通过单击按钮逐个发生多个事件?在订单中。 [英] How multiple events happen one by one by clicking a button? In an order.

查看:80
本文介绍了如何通过单击按钮逐个发生多个事件?在订单中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好



我是C#的新手。



我想制作一个基本的应用程序通过单击一个按钮在不同的文本框中显示两条消息。第二条消息大部分在两秒钟后出现。



我尝试过以下不起作用的代码。确实两条消息都会在两秒钟后立即显示。



我尝试过的事情:



Hello

I am new in C#.

I want to make an basic app that shows two messages in a different text boxes by clicking one button. The second message most be appeared after two seconds.

I have tried the following code that dose not work. Indeed both of the messages are shown at once after two seconds.

What I have tried:

private void btn_play_Click(object sender, RoutedEventArgs e)
        {
                tb_hello.Text = "hello";
                Thread.Sleep(2000);
                tb_goodbye.Text = "goodbye";
        }

推荐答案

我会使用基于任务的异步模式 await Task.Delay(2000)是一个异步的等待,它不会阻止UI线程。请注意方法签名中的 async 关键字。

I would use the Task-based Asynchronous Pattern. await Task.Delay(2000) is an asynchronous 'wait' it does not block the UI thread. Note the async keyword in the method's signature.

private async void btn_play_Click(object sender, RoutedEventArgs e)
       {
           tb_hello.Text = "hello";
           await Task.Delay(2000);
           tb_goodbye.Text = "goodbye";
       }


Thread.Sleep暂停当前线程 - 这意味着在该时间段过去之前什么都不会发生。这包括显示控件的更新!由于您正在更新UI控件,因此该代码在UI线程上运行(或者您将获得交叉线程异常),这意味着在线程完成休眠之前无法遵守更新实际显示的Paint请求,并且事件处理程序退出。



相反,显示第一条消息然后启动计时器以用第二条消息替换它。

在实践中,我' d有一个全时运行的计时器,并使用计时器事件处理程序中减少的计数器来决定何时替换消息 - 这是一个更简单的解决方案,不会冒多个计时器同时运行的风险 - 它们使用的资源是这是一个坏主意。
Thread.Sleep suspends the current thread - which means that nothing at all happens until the period has elapsed. And that includes updates to display controls! Since you are updating UI controls, that code is running on the UI thread (or you'd get a cross threading exception) which means that Paint requests to update the actual display can't be honoured until the thread has finished sleeping, and the event handler exits.

Instead, show the first message then start a timer to replace it with the second.
In practice, I'd have a timer running full time, and use a counter that is reduced in the timer event handler to decide when to replace the message - it's a simpler solution that doesn't risk multiple timers running at the same time - they use resources that are scarce so that's a bad idea.


使用一个或多个DispatcherTimers更新独立控件;特别是在WPF中。



因为它们在UI线程上运行,所以它们非常适合更新控件。



DispatcherTimer - 完整的WPF教程 [ ^ ]
Use one or more DispatcherTimers to update independent controls; particularly in WPF.

Since they run "on the UI thread", they are ideally suited for updating controls.

The DispatcherTimer - The complete WPF tutorial[^]


这篇关于如何通过单击按钮逐个发生多个事件?在订单中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆