Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#显示线程无效的跨线程访问问题_C#_Multithreading_Error Handling - Fatal编程技术网

c#显示线程无效的跨线程访问问题

c#显示线程无效的跨线程访问问题,c#,multithreading,error-handling,C#,Multithreading,Error Handling,我的代码显示行中的线程无效跨线程访问 label_mytimer.Text=mytimeLeft+“秒”;在调试中运行时,但在正常执行时,没有问题。如何避免多线程访问,我知道问题是许多线程试图同时访问我的textbox控件,不知道如何使用backgroundworker private void ttOnTimedEvent(object source, ElapsedEventArgs e) { if (mytimeLeft > 0) {

我的代码显示行中的线程无效跨线程访问 label_mytimer.Text=mytimeLeft+“秒”;在调试中运行时,但在正常执行时,没有问题。如何避免多线程访问,我知道问题是许多线程试图同时访问我的textbox控件,不知道如何使用backgroundworker

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;

        }

您可以使用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);
 }

您只能从UI线程访问Winform对象(这可能是太多的泛化)“Error 1 Type expected”一词上的“delegate”应该是可用的,请确保使用delegate not DelegateFwiw这必须写成MethodInvoker mi=new MethodInvoker(delegate{…code…});