You should, in general, leave this to a specific user interface class library in order to properly set this up. Winforms automatically installs an instance of WindowsFormsSynchronizationContext, WPF sets DispatcherSynchronizationContext, ASP.NET sets AspNetSynchronizationContext, Store application sets WinRTSynchronizationContext, etc. Highly specialized synchronization providers that are tuned to how the UI thread dispatches events.
Something special about how these application environments use their main thread. All of them implement a dispatcher loop and use a thread-safe queue to receive notifications. Commonly known as the "message loop" in the Windows GUI software. This is a general solution to the producer / consumer problem, while the dispatch cycle implements the consumer.
Creating your own synchronization provider for a workflow first requires that such a thread implement the same mechanism. In other words, you will need a thread-safe queue, such as ConcurrentQueue, and the stream must be recorded to retrieve the notifications from the queue and execute them. A delegate object would be a good choice. Now you have no problem implementing the Post method, just add the SendOrPostCallback delegate to the queue. To implement the sending method, additional work is required, the flow should signal that the delegate has been received and completed. Thus, the queue object also needs AutoResetEvent.
Please note that your stream now ceases to become a generally useful stream, it is bogged down by sending these notifications. And as existing synchronization providers already do all this. Therefore, if your application is a Winforms application, you can also call Application.Run () on your workflow with a dummy invisible form. And you will automatically receive your synchronization provider for free.
Hans passant
source share