Total Pageviews

Saturday 25 February 2012

How to Cross-thread operation

The same control can't be accessed by multiple threads. in that case the following code is helpful
private void Form1_Load(object sender, EventArgs e)
{

    Thread t1 = new Thread(new ParameterizedThreadStart(printThr1));
    Thread t2 = new Thread(printThr2);
    t1.Start("U");
    t2.Start();
}
private void printThr1(object t)
{
           

    for(int i=1;i<600000;i+=2)
    {
        if (txtControl.InvokeRequired)
        {
            txtControl.Invoke(new MethodInvoker(delegate { txtControl.Text += Environment.NewLine + t.ToString()+"= " + i; }));
            Thread.Sleep(500);
        }
    }
}
private void printThr2()
{
           
    for (int i = 0; i < 50000; i += 2)
    {
              
        if (txtControl.InvokeRequired)
        {
            txtControl.Invoke(new MethodInvoker(delegate { txtControl.Text += Environment.NewLine + "N= " + i; }));
            Thread.Sleep(300);
        }

    }
}


No comments:

Post a Comment