First of all, we need to say what a synchronization context is.
A synchronization context is a class that determines which stream operations should be performed.
The main synchronization context classes β Sync Context and Windows Forms SynchronizationContext β are simply simple classes that can delegate operations to other threads.
The SynchronizationContext.Post () method simply delegates the operation to some thread from the thread pool (using the ThreadPool.QueueUserWorkItem (...) method inside).
The SynchronizationContext.Send () method simply executes the delegate in the same thread.
The most common use of WindowsFormsSynchronizationContext is as follows: WindowsFormsSynchronizationContext is internally configured for the main GUI stream when creating the main form of your application. Later, this synchronization context is used to execute delegates in the same main GUI thread.
So, I will conclude: the synchronization context is a simple class that decides in which thread the delegation will be performed.
Now back to the AsyncOperationManager class.
You can use the AsyncOperationManager class when you need to perform an operation in some synchronization context. The cotnext synthesizer on which the operation will be performed may be:
1) The same synchronization context in which you call the AsyncOperationManager.CreateOperation () method if the stream has a specific SynchronizationContext.
or
2) A new syncronization context (represented by a new instance of the SynchronizationContext base class) if the current thread does not yet have a synchronization context. An instance of the base class SynchronizationContext, as I said earlier, will delegate over a certain thread from the thread pool.
Basically, AsyncOperationManager is just a helper class that uses the AsyncOperation and SynchronizationContext inner classes.
Now about usage scenarios.
For example, in your main GUI thread, you create a class that provides asynchronous operations using an event-based async pattern (i.e., it provides progress reporting events).
You want the event handlers to run in the same GUI thread, so you can work with the GUI controls from the event handlers.
In this case, in the OperationAsync method, you create an AsyncOperation object and save it for later use:
public void OperationAsync(object arg1, object arg2, ...) { _asyncOperation = AsyncOperationManager.CreateOperation(null); ... }
And when the operation completes, you raise the OperationCompleted event using the AsyncOperation.Post () method. If you run the AsyncOperationManager.CreateOperation () method from the GUI thread of your application, the event handlers will execute in the same thread, i.e. in your main GUI thread:
private void OnOperationCompleted(AsyncCompletedEventArgs e) { EventHandler<AsyncCompletedEventArgs> handler = OperationCompleted; if(handler != null) { _asyncOperation.Post( delegate { handler(this, e); }, null); _asyncOperation.OperationCompleted(); } .... }