Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Thread.Sleep in 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.

What is wrong with my code?

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();
like image 399
KMC Avatar asked Dec 04 '25 17:12

KMC


1 Answers

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);
        }
    }
like image 76
Rafal Avatar answered Dec 06 '25 08:12

Rafal