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