Why is Task.WhenAll() blocking here?

試著忘記壹切 提交于 2020-12-31 11:52:31

问题


I have a fairly simple code snippet but it seems it blocks on Task.WhenAll(). The Main function just calls new Test(). Can someone help find the root cause?

internal class Test
{
    public static async Task<int> Foo()
    {
        return 0;
    }

    static Test()
    {
        var taskList = new List<Task>();

        for (int i = 0; i < 100; i++)
            taskList.Add(Task.Run(() => Foo()));

        Task.WhenAll(taskList.ToArray()).GetAwaiter().GetResult();
    }
}

回答1:


The CLR takes a global lock when running a static constructor. The static constructor must release this lock before other threads can enter any method on the class. This is to provide the guarantee that the static constructor is run and has completed only once per appdomain. Here is the same problem with the threading made more explicit.

class Test
{
    static Test() {
       var thread = new Thread(ThreadMethod);
       thread.Start();
       thread.Join();
    }

    private static void ThreadMethod()
    {
    }
}

The new thread cannot enter ThreadMethod until the static constructor exits, but the static constructor cannot exit until the thread ends, a deadlock.

Your example is just a more complicated version of this that uses Task.Run instead of creating a Thread and starting it and then GetResult blocks the same way that Thread.Join does.




回答2:


You are deadlocking. Note that your code is in the static constructor for your class. This means that no other type initialization can occur until your type initializer finishes. But your type initializer won't finish until all those tasks finish. But if those tasks rely on some other type that hasn't been initialized yet, they can't finish.

The solution is to implement this initialization you're trying to do via some other mechanism. Start the tasks in the static constructor if you want, but fix your code so that your instances can wait on the result outside of the static constructor. For example, instead of using the static constructor, use Lazy<T>:

private static readonly Lazy<int> _tasksResult = new Lazy<int>(
    () => InitTest());

static int InitTest()
{
    var taskList = new List<Task>();

    for (int i = 0; i < 100; i++)
        taskList.Add(Task.Run(() => Foo()));

    return Task.WhenAll(taskList.ToArray()).GetAwaiter().GetResult();
}

Or something like that (it's not really clear what result you're actually interest in here, so the above has a bit of hand-waving in it).



来源:https://stackoverflow.com/questions/27389142/why-is-task-whenall-blocking-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!