0

How to execute method in main thread, when I am in secondary thread, but in Console application? I tried something like this, but context is null because I am using console application.

static void Main(string[] args)
{
    Thread t = new Thread(new ThreadStart(Worker));
    t.Start();
    t.Join();
}

static void Worker()
{
    // Create a SynchronizationContext object for the current thread
    SynchronizationContext context = SynchronizationContext.Current;

    // Call the HelloWorker method on the main thread using the SynchronizationContext
    context.Post(new SendOrPostCallback(HelloWorker), null);
}

static void HelloWorker(object state)
{
    // Code in this method will be executed on the main thread
    Console.WriteLine("Hello from the main thread! Thread ID: " + Thread.CurrentThread.ManagedThreadId);
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • 1
    What exactly are you actually trying to do? – Fildor Apr 21 '23 at 10:53
  • Your main thread is stuck waiting for the other thread to complete -- the way you have set it up you cannot execute anything on that thread. That thread needs to be waiting on some signal to wake up and have some point in memory to go look for work to do. – odyss-jii Apr 21 '23 at 10:54
  • 1
    No can do. In a UI application, the main thread processes things from a message queue, and other threads can post things to the message queue to be executed by the main thread. In a console app, the main thread just executes your Main method -- there's no message queue, so no way for other threads to send things to the main thread – canton7 Apr 21 '23 at 10:55
  • 1
    @canton7 unless he sets up a message queue of course. Which is trivial if you just want a bare minimum working example: just use a `BlockingCollection`. – odyss-jii Apr 21 '23 at 10:56
  • 1
    Possible duplicate of [How to switch execution from worker to main thread in a console application?](https://stackoverflow.com/q/67007293/11683) (no answer). – GSerg Apr 21 '23 at 10:57
  • 2
    @odyss-jii Yep! See https://stackoverflow.com/a/67333366/1086121 – canton7 Apr 21 '23 at 10:59
  • @Fidor - We have runtime in C# that is used by application writen in delphi. It functions on some callbacks to delphi, but i have situation where i have secondary thread in my C# dll and should execute some callback method in main thread. long story short if it will function in simple console application it will work in my case. – Pavel Vlasák Apr 21 '23 at 11:03
  • Also, the "main thread" in UI applications is special because only one thread is allowed to manipulate UI primitives. There's nothing "special" about the first thread in a UI app (insert usual caveats about simplifying UI, etc) – Damien_The_Unbeliever Apr 21 '23 at 11:03
  • _"... and should execute some callback method in main thread"_ - sounds like you want something like a blocking queue. – Fildor Apr 21 '23 at 11:11

0 Answers0