Thread.Sleep 'breaks' Task

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?

Answers


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

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

Need Your Help

egit: changes made in one branch are visible on another branch without any commit

git branch egit master

I am using egit and this is what I see. Don't really understand how this works

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.