1

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?

3 Answers 3

3

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();
3

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();
1
  • I chose the other answer because of the additional details
    – MikeSW
    Nov 30, 2011 at 8:52
0

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();
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.