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

前端 未结 3 898
天涯浪人
天涯浪人 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:06

    The context is very important here. When you start a task like this, it uses the current scheduler - and if that assumes it will be able to use the current thread, you'll effectively deadlock when you wait for it.

    The same code in different context would be fine.

    The reason others are saying it's working for them, but it's not working for you, is that no doubt you're running this code in a different context to other people - but you haven't shown us a short but complete program, just this snippet, so everyone is trying to reproduce it in a different way. (I see you've now uploaded a project, which will no doubt shed more light. A short but complete program which could be posted in the question is generally preferable, of course.)

提交回复
热议问题