Why will an empty .NET Task not complete if started and waited for from a static constructor?

前端 未结 3 934
天涯浪人
天涯浪人 2020-12-31 23:54

I cannot understand why the following code will not work:

var task = new Task(() => { });
task.Start();
if (task.Wait(10000))
{
   logger.Info(\"Works\");         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 00:02

    Thank you everyone for your comments, it helped me be more specific and finally isolate the issue.

    I created a test project here: http://erwinmayer.com/dl/TaskTestProject.zip. It shows that the code in my question doesn't work if it runs within the static constructor. But it does work if called directly as a static class method, after the static constructor has been initialized.

    This recent MSDN blog post provides some technical insight on the existence of related issues when dealing with multithreading and static constructors:

提交回复
热议问题