C# - Invoke vs BeginInvoke
From Microsoft
BeginInvoke - Executes a delegate asynchronously on the thread that the control's underlying handle was created on.
Invoke - Executes the specified delegate on the thread that owns the control's underlying window handle.
Most often, we will use these with delegate, especially, to prevent cross thread exception when you are trying to access UI components with another thread.
From their definition, BeginInvoke is a asynchronous version of Invoke. Although you may not take it to heart at first glance, you will encounter their different when you are playing around with it.
Invoke, since it is synchronous, it will ask the UI thread to do the delegate job and wait for it returns.
BeginInvoke, since it is asynchronous, it will post the delegate job to UI thread and schedule it for a time to execute while it will continue to do it current job.
The complication is Invoke may cause deadlock situation if you are not careful with your code
Imagine, thread 1 access to UI thread, and now, the UI thread wants to access thread 1 for some logic calculation. Since thread 1 is waiting for UI thread to return, a deadlock occurs.
Also, Invoke causes OS to context switch immediately. If you constantly calling Invoke, it will hamper your application performance.
But, on the other hand, BeginInvoke schedule your delegate method to be done some time in the future. Thus, it is not suitable for time-sensitive situation that execution delay is not tolerable.
Invoke is synchronous, thus used when immediate execution and result is required before further action is to be done.
ReplyDeleteOn the other hand. BeginInvoke is asynchronous, which is normally used for code that executes slowly which may hog up the entire UI thread, which will cause the UI to freeze. E.g. sending of email and other I/O bound operations. In such cases, it will be better to process such tasks asynchronously in the background, and have them call back the UI thread through EventListeners on the main UI object. Though the callbacks, the UI can update the end-user on the status of the background tasks just being executed.