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;

        }
4

1 回答 1

0

您可以使用 MethodInvoker 在 GUI 线程上运行

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);
 }
于 2013-03-23T15:48:27.390 回答