How to Thread.Sleep in BeginInvoke

旧时模样 提交于 2019-12-02 02:16:07

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

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.

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();

Your code creates new thread only to force dispatcher to synchronize your action back to UI thread. I suppose that you added Dispatcher.BeginInvoke due to exception that changing mytxt1.Text from another thread causes. Try this:

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);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!