1

I have the following code:

static async Task Main()
{
    // Save the id of the thread that runs Main
    var n = Thread.CurrentThread.ManagedThreadId;

    // We will be working in a different thread 
    var _ = Task.Run(() =>
    {
        // We will periodically do this:
        while (true)
        {
            // Get some input

            // Process it in a different thread
            Task.Run(() =>
            {
                // Assume I do some heavy calculations here...

                // Does every happen that the thread which runs Main is here?
                if (Thread.CurrentThread.ManagedThreadId == n)
                    Console.WriteLine("It happens");

                // It turns out it does not :/
            });
        }
    });

    // Keep the application alive
    await Task.Delay(-1);
}

When I run this, I will never see It happens printed. I would like that to happen because now it seems to me like the thread that runs the Main method is doing nothing and I think it is a good idea to reuse it for the heavy computation. Can I change await Task.Delay(-1) to achieve so?

Patrik Bak
  • 528
  • 1
  • 7
  • 14
  • Why not simply `await Task.Run()`? – aepot Jul 18 '20 at 15:55
  • It's not so simple. [Does this answer your question?](https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/) – aepot Jul 18 '20 at 15:59
  • Short version: `Task.Run()` by default will _never_ execute the task on the original thread, even when a synchronization context exists, and in a console program it doesn't. If a synchronization context exists, the continuation of an `async` method (i.e. after `await` completes) is run in that context if a) the `await` itself was executed in the context, and b) the behavior wasn't modified by calling `ConfigureAwait(false)`. See marked duplicate for more explanation. The `Task.Run()` task is run in a thread determined by the scheduler, which by default uses the thread pool only. – Peter Duniho Jul 18 '20 at 17:39
  • See also https://stackoverflow.com/questions/20300164/run-code-in-main-thread, https://stackoverflow.com/questions/20942253/default-synchronizationcontext-vs-default-taskscheduler, and https://stackoverflow.com/questions/52686862/why-the-default-synchronizationcontext-is-not-captured-in-a-console-app – Peter Duniho Jul 18 '20 at 17:41

0 Answers0