N
N
NameOf Var2019-03-13 16:01:40
.NET
NameOf Var, 2019-03-13 16:01:40

Why does Task.WhenAll() hang when doing multiple tasks?

I want to run multiple tasks at the same time

static async void TestMethod()
        {
            Task<string>[] allTasks = new Task<string>[5];

            for(int i = 0; i < 5; i++)
            {
                int j = i;
                allTasks[i] = new Task<string>(() => { return "#" + j; });
            }

            var resultTask = Task.WhenAll(allTasks);
            Console.WriteLine(resultTask.Status);

            var result = resultTask.Result;

            foreach (var res in result)
            {
                Console.WriteLine("1");
                Console.WriteLine(res);
            }

            Console.WriteLine("END");
        }

But this code freezes after the execution of WhenAll, the resultTask has the WaitingForActivation status, the execution never reaches the line resultTask.Result

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2019-03-13
@hax

The constructor new Task({} => {})only initiates the task.
It can then be put to execution by calling the Start method.
Example:

var task = new Task({} => {});
task.Start();

You can also start a task using the Task.Run или TaskFactory.StartNewmethods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question