0

I have form with button and text box. Button is starting thread which is updating value of text box.

    public Form1()
    {
        InitializeComponent();
        myDelegate = new UpdateUi(updateUi);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        myThread = new Thread(new ThreadStart(ThreadFunction));
        myThread.Start();
    }
    private void ThreadFunction()
    {
        MyThreadClass myThreadClassObject  = new MyThreadClass(this);
        myThreadClassObject.Run();
    }
    private void updateUi(int i)
    {
        textBox1.Text = i.ToString();
        Thread.Sleep(1000);
    }
    public Thread myThread;
    public delegate void UpdateUi(int i);
    public UpdateUi myDelegate;

and ThreadClass:

public class MyThreadClass
{
    Form1 myFormControl1;
    public MyThreadClass(Form1 myForm)
    {
        myFormControl1 = myForm;
    }

    public void Run()
    {
        // Execute the specified delegate on the thread that owns
        // 'myFormControl1' control's underlying window handle.
        for(int i=0;i<100;i++)
        {
            if(myFormControl1.InvokeRequired)
            {
                myFormControl1.Invoke(myFormControl1.myDelegate,i);
            }

        }


    }
}

As You can see there is nothing special in my code but sometimes the code freeze.

eg it goes 1->2->3->freeze->16->17 and so on.

I took code from HERE with little modifications

szpic
  • 4,346
  • 15
  • 54
  • 85

1 Answers1

1

The issue is you are delaying the UI thread not the the process itself so what happens is you issue all the update commands but since it all runs on the same thread it gets clogged because the Thread.Sleep stops the UI thread so it runs a bunch of textBox1.Text = i.ToString(); then it stops for all the time of all the Thread.Sleep(1000); probably the number of 1->2->3... you see is equal to the number of cores in your machine.

When you stop the run method what happens is you issue one update command that runs immediately and wait for one second until you issue the next command witch I think its what you are trying to accomplish.

Pedro.The.Kid
  • 1,968
  • 1
  • 14
  • 18