Search code examples
c#.netwinformsmessagebox

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.


Solution

  • 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.