derekhh
derekhh

Reputation: 5532

Why is Task.WhenAll() blocking here?

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

Upvotes: 3

Views: 2218

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40818

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.

Upvotes: 10

Peter Duniho
Peter Duniho

Reputation: 70652

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).

Upvotes: 3

Related Questions