Question

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?

Was it helpful?

Solution

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:

var task = Task.Factory.StartNew( d );
task.Wait();

OTHER TIPS

Are you waiting for the task to finish anywhere, or does your program quit before the task is done?

Task task = Task.Factory.StartNew(d);
task.Wait();

I've just run your code and it outputs:

Task: 10 log:0
Task: 10 log:1
Task: 10 log:2
Task: 10 log:3
Task: 10 log:4
Task: 10 log:5
Task: 10 log:6
Task: 10 log:7
Task: 10 log:8
Task: 10 log:9
Task: 10 log:10

Here is the code of console based on your code app I've run:

using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      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);
      Console.ReadLine();
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top