如何在BeginInvoke中进行Thread.Sleep [英] How to Thread.Sleep in BeginInvoke

查看:166
本文介绍了如何在BeginInvoke中进行Thread.Sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码将 TextBox.Text 更新为从1到10,内部显示时间为1秒.我不明白为什么整个UI在文本更新为10之前要睡10秒钟,因为 Thread.Sleep(1000)应该属于 Dispatcher创建的单独的后台线程.BeginInvoke .

I tried to update a TextBox.Text to display from 1 to 10 with an internal of 1 second with the following code. I do not understand why the entire UI sleeps for 10 second before the text is updated to 10, as I though the Thread.Sleep(1000) should belong to a separate background thread created by Dispatcher.BeginInvoke.

我的代码有什么问题?

Thread t1 = new Thread(new ThreadStart(
    delegate()
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            new Action(delegate()
                {
                    for (int i = 1; i < 11; i++)
                    {
                        mytxt1.Text = "Counter is: " + i.ToString();
                        Thread.Sleep(1000);
                    }
                }));

    }));
t1.Start();

推荐答案

设置文本的操作在UI界面上运行,这就是UI冻结的原因.

The Action that sets the text is running on the UI thred and that's why the UI is freezing.

由于受限于只有创建UI控件实例(即UI线程)的线程才能修改UI控件的属性,因此您必须运行在UI线程上设置文本的代码.这就是您正在做的.

Due to the limitation that only the Thread that created the instances of UI controls (a.k.a. the UI thread) can modify properties of UI controls, you have to run the code that sets the text on the UI thread. And that's what you're doing.

您可以尝试的是在Threading.Timer中运行该代码.

What you can try, is to have that code run in a Threading.Timer.

或者...使用您已经拥有的代码,您应该具有类似的内容,并且可能会起作用:

Or...with the code you already have, you should have something like this and it might work:

Thread t1 = new Thread(new ThreadStart(
delegate()
{
    for (int i = 1; i < 11; i++)
    {
    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
        new Action(delegate()
            {                        
                    mytxt1.Text = "Counter is: " + i.ToString();                           

            }));
     Thread.Sleep(1000);
     }             
}));
t1.Start();

这篇关于如何在BeginInvoke中进行Thread.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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