如何在BeginInvoke中使用Thread.Sleep

KMC*_*KMC 2 c# wpf multithreading dispatcher

我尝试使用以下代码更新TextBox.Text以显示1到10,内部为1秒.我不明白为什么整个UI在文本更新到10之前会休眠10秒,因为我虽然Thread.Sleep(1000)应该属于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();
Run Code Online (Sandbox Code Playgroud)

Raf*_*fal 6

您的代码仅创建新线程以强制调度程序将您的操作同步回UI线程.我想你是Dispatcher.BeginInvoke因为异常而添加的,因为mytxt1.Text从另一个线程改变了.试试这个:

Thread t1 = new Thread(new ThreadStart(
    delegate()
    {
        for (int i = 1; i < 11; i++)
        {        
            var counter = i; //for clouser it is important
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(delegate()
                {                    
                    mytxt1.Text = "Counter is: " + counter.ToString();                                         
                }));
           Thread.Sleep(1000);
        }
    }
Run Code Online (Sandbox Code Playgroud)