【问题标题】:c# shows thread invalid cross-thread access issues [duplicate]c#显示线程无效的跨线程访问问题[重复]
【发布时间】:2013-03-23 23:53:02
【问题描述】:

我的代码在行中显示线程无效的跨线程访问 label_mytimer.Text = mytimeLeft + "秒";在调试时运行,但在正常执行时,没有问题。如何避免多跨线程访问,我知道问题是许多线程试图同时访问我的文本框控件,不知道如何使用 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;

        }

【问题讨论】:

  • 您只能从 UI 线程访问 Winform 对象(这可能过于笼统)

标签: c# multithreading error-handling


【解决方案1】:

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

【讨论】:

  • “错误 1 ​​类型预期”在“代表”一词上
  • 它应该可用,确保你使用委托而不是委托
  • Fwiw 这必须写成 MethodInvoker mi = new MethodInvoker(delegate { ...code... });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多