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?