0

My code shows thread invalid cross-thread access in the line label_mytimer.Text = mytimeLeft + " Sec"; when running in the debugging, but in normal execution, it has no problem. How can I avoid the multi cross thread access, I know the problem is that many threads try to access my textbox control at same time, don't know how to use backgroundworker if it works.

private void ttOnTimedEvent(object source, ElapsedEventArgs e)
    {
        if (mytimeLeft > 0)
        {

            // Display the new time left
            // by updating the Time Left label.
            mytimeLeft = mytimeLeft - 1;
            label_mytimer.Text = mytimeLeft + " Sec";//Show time left
        }
        else
        {

            label_mytimer.Text = "OK...";
            mytimeLeft = int.Parse(tBox_rp_Time.Text);

            mycountdownTimer.Stop();
            mycountdownTimer.Enabled = false;

        }
Wendy Lam
  • 21
  • 5
  • You can only access Winform objects from the UI thread (that might be too much of a generalisation) – Rob Mar 23 '13 at 15:49

1 Answers1

0

You can use MethodInvoker to run on GUI thread

private void ttOnTimedEvent(object source, ElapsedEventArgs e)
{       
    MethodInovker mi = new delegate{
    if (mytimeLeft > 0)
    {
        // Display the new time left
        // by updating the Time Left label.
        mytimeLeft = mytimeLeft - 1;
        label_mytimer.Text = mytimeLeft + " Sec";//Show time left
    }
    else
    {
        label_mytimer.Text = "OK...";
        mytimeLeft = int.Parse(tBox_rp_Time.Text);
        mycountdownTimer.Stop();
        mycountdownTimer.Enabled = false;
    }
    };
    if(InvokeRequired)
       this.Invoke(mi);
 }
Adil
  • 146,340
  • 25
  • 209
  • 204