So I have the following code
Action d = () =>
{
for (int i = 0; i <= 10; i++)
{
Thread.Sleep(50);
Console.WriteLine("Task: {0} log:{1}",Thread.CurrentThread.ManagedThreadId,i);
}
};
Task.Factory.StartNew(d);
However it doeasn’t output anything. But if I comment Thread.Sleep, it works as expected. Playing with different Sleep values gets me more or less results depending on the value.
Why does it happen this way?
I suspect your program is exiting before the task has a chance to run.
Tasks run on thread pool threads by default, which are background threads. That means your program doesn’t wait for them to finish before exiting.
Try adding this on your main thread: