简体   繁体   English

如何使用BeginInvoke for button.PerformClick()从另一个线程 - 跨线程调用

[英]How to use BeginInvoke for button.PerformClick() from another thread - cross threaded call

I have a method: 我有一个方法:

 private void RecordButton_Click(object sender, EventArgs e) {

  }

and in the other method which was called by other thread: 在另一个线程调用的另一个方法中:

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

I get an exception that indicates the PerformClick() is invoked in the other thread therefore I should make a cross thread call. 我得到一个异常,表明在另一个线程中调用了PerformClick() ,因此我应该进行跨线程调用。 What should I write instead to PerformClick() ? 我应该写什么代替PerformClick()

here how you can by pass this exception 这里你怎么能通过这个例外

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

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

               RecordButton.PerformClick();
            }

        }

or you can use BeginInvoke which executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. 或者您可以使用BeginInvoke,它在创建控件的基础句柄的线程上异步执行指定的委托。

  private void raiseAlarm()
        {

            this.BeginInvoke(new Action(raiseAlarm)); 



        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM