Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i want to count 0 to 1000 and write in textbox using thread
this is my code but its not doing and after a few second it go to debugger.break();
what should i do to it run correctly?
C#
private void loop()
{
    while (check == true)
    {
        Dispatcher.BeginInvoke(() =>
           {
               for (int i = 0; i < 1000; i++)
               {
                   Thread.Sleep(100);
                   txtResult.Text = i.ToString();
               }
           });
    }
}

private void btnClick_Click(object sender, RoutedEventArgs e)
{
    check = true;
    ThreadStart st = new ThreadStart(loop);
    Thread s = new Thread(st);
    s.Start();
}

With Respect
Posted

1 solution

Right now, you keep invoking a method on the dispatcher thread that loops from 0 to 1000, and it blocks the dispatcher thread 100 milliseconds while it is in that loop. You should not be blocking the dispatcher thread, only block your loop thread. Also, I think you probably want an if instead of a while.

Try this:
C#
private void loop()
{
    if (check)
    {
        for (int i = 0; i < 1000; i++)
        {
            Thread.Sleep(100);
            Dispatcher.Invoke(() =>
            {
                txtResult.Text = i.ToString();
            }
        }
    }
}
 
Share this answer
 
v2
Comments
Avenger1 8-Feb-15 10:01am    
thanks
i wrote while because my last code just could work with while i i forgot to change it
thanks again
Thomas Daniels 8-Feb-15 10:02am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900