Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Invoking and BeginInvoking a MessageBox?

In a form, compare

BeginInvoke (new Action (() => {
    MessageBox.Show ());
}));

with

Invoke (new Action (() => {
    MessageBox.Show ());
}));

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.

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.

like image 938
mafu Avatar asked May 12 '10 13:05

mafu


People also ask

What is the difference between Invoke and BeginInvoke?

Invoke : Executes on the UI thread, but calling thread waits for completion before continuing. Control. BeginInvoke : Executes on the UI thread, and calling thread doesn't wait for completion.

What is Startinvoke C#?

BeginInvoke(Action) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. BeginInvoke(Delegate) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.


1 Answers

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");

You should see output similar to the following, where the "BeginInvoke" text is delayed due to its asynchronous execution:

AfterBeginInvokeCalled
Invoke
AfterInvokeCalled
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.

like image 126
Jeff Yates Avatar answered Oct 04 '22 23:10

Jeff Yates