I have a .NET console app, which among other things, listens for various external events (websockets, udp, etc...). When the event arrives, it does so on a worker thread. I am trying to marshal the event processing to the main thread (defined as where void Main() was kicked off).
Somewhat similar question have been asked before but it deals with calling out to Windows API. It allowed me to try out various ideas that ultimately didn't work.
I understand that to marshal threads you must have SynchronizationContext and console apps, unlike WinForms and WPF, do not have it.
I attempted to use a custom SyncronizationContext, but it just doesn't marshal threads.
So in a code like this, is it possible to Marshal execution to the main thread?
static void Main() {
WebSocketListener.Register(ReceiveMessages);
}
static void ReceiveMessages(Message message) {
// fires on a worker thread
MarshalToMainThread.Post(() => ProcessOnMainThread());
}
static void ProcessOnMainThread() {
}