是什么调用和BeginInvoking一个MessageBox之间的区别? [英] What is the difference between Invoking and BeginInvoking a MessageBox?
问题描述
在一个表格,比较
BeginInvoke (new Action (() => {
MessageBox.Show ());
}));
与
with
Invoke (new Action (() => {
MessageBox.Show ());
}));
的区别是什么,当我应该使用一个比其他?如何受的MessageBox的消息泵的行为?
What is the difference, and when should I use one over the other? How is the behavior affected by the message pump of the MessageBox?
我做了一些测试,发现的两个方法阻止用户界面。
I did some testing and found that both methods block the UI.
唯一的区别是,调用实际上是瞬间称为一段时间,直到代码运行的BeginInvoke需要(很短)的时间。这是可以预料的。
The only difference is that Invoke is actually called instantly while BeginInvoke takes a (very short) time until the code is run. This is to be expected.
推荐答案
的 的BeginInvoke
将异步调用该委托,独立有排队的执行委托立即返回当前线程。
BeginInvoke
will invoke the delegate asynchronously, returning immediately having queued the delegate for execution independently of the current thread.
的 调用
将同步调用委托,到委托完成阻塞调用线程。
Invoke
will invoke the delegate synchronously, blocking the calling thread until the delegate completes.
要看到其中的差别,试试下面的代码:
To see the difference, try the following code:
BeginInvoke(new Action(()=>Console.WriteLine("BeginInvoke")));
Console.WriteLine("AfterBeginInvokeCalled");
Invoke(new Action(()=>Console.WriteLine("Invoke")));
Console.WriteLine("AfterInvokeCalled");
您应该看到类似以下,其中BeginInvoke的文本由于延迟到它的异步输出执行:
You should see output similar to the following, where the "BeginInvoke" text is delayed due to its asynchronous execution:
AfterBeginInvokeCalled结果
调用结果
AfterInvokeCalled结果
的BeginInvoke
AfterBeginInvokeCalled
Invoke
AfterInvokeCalled
BeginInvoke
对于你观察到的,因为它仅仅是调用的委托,为同步或异步的行为的行为;该方法的内容很可能导致调用线程停止或用户界面被阻塞。在示出的消息框,无论代表是否使用的 的BeginInvoke
与否,一旦委托被调用时,用户界面将会被阻塞,直到消息框被驳回。
Regarding the behaviour you observe, as it is only the act of calling the delegate that is synchronous or asynchronous; the content of the method may well cause the calling thread to stop or the UI to be blocked. In the case of showing a message box, regardless of whether the delegate is delayed using BeginInvoke
or not, once the delegate is called, the UI will be blocked until the message box is dismissed.
这篇关于是什么调用和BeginInvoking一个MessageBox之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!