Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are difference between using Invoke and SynchronizationContext.Post object?

When I received an exception that is related with thread context, I use delegate function and I invoke this delegate function. It is necessary for use control from an other thread. But I've just learned that I can use SynchronizationContext.Post() function and I can call my delegate in this method.

I'm not sure which one is better? What are differences between these methods?

like image 796
golazo Avatar asked Feb 14 '14 11:02

golazo


2 Answers

It is the same thing, SynchronizationContext.Post() calls BeginInvoke() and Send() calls Invoke().

The key property of SynchronizationContext is that there is more than one implementation of it. Important ones are WindowsFormsSynchronizationContext, it uses Control.Begin/Invoke and DispatcherSynchronizationContext, it uses Dispatcher.Begin/Invoke. There are others for ASP.NET, Windows Store (aka WinRT, aka Universal) apps, out-of-process servers that are COM+ hosted, etcetera.

The extra level of indirection helps avoid taking a dependency on the specific method that invokes. Important for any class library of course.

like image 171
Hans Passant Avatar answered Sep 21 '22 12:09

Hans Passant


Control.Invoke is equivalent to SynchronizationContext.Send in that both are synchronous. Control.BeginInvoke is equivalent to SynchronizationContext.Post in that both are asynchronous. Use any of these 4 methods to prevent a cross-thread exception.

Use SynchronizationContext to encapsulate thread marshaling code. For example, Form1 creates object Worker to do some work on a different thread. The constructor for Worker captures the current (i.e. Form1's) SynchronizationContext. When Worker produces data to display on Form1, Worker can use the captured SynchronizationContext to synchronize to Form1's thread before sending a notification, e.g. event, to Form1. This means that Form1 does not need to know about the different thread, does not need to call InvokeRequired, and has less code. It also means that Worker does not need to know that its client is a Form.

Below is an excellent series explaining SynchronizationContext:

Understanding SynchronizationContext - Part I

Understanding SynchronizationContext - Part II

Understanding SynchronizationContext - Part III

like image 35
groverboy Avatar answered Sep 22 '22 12:09

groverboy