Why the empty .NET task will not be completed if it is started and will wait from the static constructor?

I can’t understand why the following code will not work:

var task = new Task(() => { }); task.Start(); if (task.Wait(10000)) { logger.Info("Works"); } else { logger.Info("Doesn't work"); } 

The status of the task is delayed by the "Run" after the timeout, although nothing can be done. Replacing task.Start() with task.RunSynchronously() will work.

Does anyone have an idea of ​​what I can do wrong?

A test project for replicating a problem is available here: http://erwinmayer.com/dl/TaskTestProject.zip . As far as I can see, this does not work if the method with the above code works inside the static constructor. But it works if called directly as a method of a static class.

This latest MSDN blog post seems to highlight related issues with static constructors: http://blogs.msdn.com/b/pfxteam/archive/2011/05/03/10159682.aspx

+6
c # asynchronous wpf task-parallel-library
source share
3 answers

Thanks to everyone for your comments, this helped me to be more specific and finally isolate the problem.

I created a test project here: http://erwinmayer.com/dl/TaskTestProject.zip . It shows that the code in my question does not work if it works in a static constructor. But it works if called directly as a method of a static class after initializing the static constructor.

This latest MSDN blog post provides some technical information on the existence of related issues when working with multi-threaded and static constructors:

+1
source share

The context is very important here. When you run such a task, it uses the current scheduler - and if it assumes that it will be able to use the current thread, you will be effectively blocked when you wait for it.

The same code in a different context will be fine.

The reason others say that it works for them, but it does not work for you, is because, no doubt, you are using this code in a different context for other people, but you have not shown us a short but complete program , just this fragment, so everyone is trying to reproduce it differently. (I see that you have now uploaded a project that will no doubt shed more light. Of course, a short, but complete program that can be posted in the question is usually preferred.)

+10
source share

Working:

  var task = new Task(() => { }); task.Start(); if (task.Wait(10000)) { Console.WriteLine("yes"); } else { Console.WriteLine("no"); } 

And it gives yes , as expected. You must do something else that makes it not work. In this form, without the context of what / where you are doing it, it works.

Even this abomination works:

  var task = new Task(() => { var task1 = new Task(() => { }); task1.Start(); if (task1.Wait(10000)) { Console.WriteLine("yes"); } else { Console.WriteLine("no"); } }); task.Start(); if (task.Wait(10000)) { Console.WriteLine("yes"); } else { Console.WriteLine("no"); } 
0
source share

All Articles