Search code examples
c#multithreadingdispatch

How can I queue a function to be invoked by the MainThread in C#?


I have found plenty of resources for how to invoke a function on the UI thread, but I have some logic that is only allowed to be run from the Main Thread. Is there a way to grab a dispatcher on the Main thread and invoke on it?


Solution

  • The "dispatcher" is a concept specific to a particular UI framework (here: WPF). There is no dispatcher you can use to target any thread. Imagine the following thread:

    while (true) Console.WriteLine("x");
    

    How are you going to invoke something on that thread? It can't be done because that thread is forever busy doing something else. It is not cooperating.

    I kind of doubt that you need to invoke something on the "main thread". But I'll answer the question literally. You need to make the main thread cooperate and accept work from other threads. Maybe a queue of Action or a boolean flag that tells that thread to do something specific.