【问题标题】:How to use BeginInvoke for button.PerformClick() from another thread - cross threaded call如何从另一个线程使用 BeginInvoke 进行 button.PerformClick() - 跨线程调用
【发布时间】:2014-01-19 17:50:37
【问题描述】:

我有一个方法:

 private void RecordButton_Click(object sender, EventArgs e) {

  }

在其他线程调用的其他方法中:

 private void raiseAlarm() {
                RecordButton.PerformClick();//EXCEPTION HERE
        }

我得到一个异常,表明 PerformClick() 在另一个线程中被调用,因此我应该进行跨线程调用。我应该写什么给PerformClick()

【问题讨论】:

  • 你使用的是 wpf 还是 winforms
  • @K.B 都在这个应用程序中,但这是相当 winforms 的一部分(此代码在 WinForms 类中)。
  • 在stackoverflow中搜索,有很多相同的问题
  • @sll 我做了,只有非常具体的,他们的问题域不包括这个问题。
  • @sll 请看一下答案下的评论。

标签: c# .net multithreading button click


【解决方案1】:

这里如何绕过这个异常

private void raiseAlarm()
        {
            if (this.InvokeRequired)
            {

                Action action = raiseAlarm;  
                this.Invoke( action); 
            }
            else
            {

               RecordButton.PerformClick();
            }

        }

或者您可以使用 BeginInvoke 在创建控件的基础句柄的线程上异步执行指定的委托。

  private void raiseAlarm()
        {

            this.BeginInvoke(new Action(raiseAlarm)); 



        }

【讨论】:

  • 使用 BeginInvoke 更好吗?
  • BeginInvoke 将启动一个异步事件,但我认为您的方案不会改变更多的事情
  • callin BeginInvoke(...) 看起来如何?我尝试了BeginInvoke(RecordButton.PerformClick),但它不起作用 -> 参数错误。
猜你喜欢
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
相关资源
最近更新 更多