I have the following class which is named Pluck:
internal static void Work()
{
Task[] tasks = new Task[5];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = SumAsync();
}
Task.WhenAll(tasks);
}
private static async Task<int> SumAsync()
{
return await Task.Run(() => { return OnePlusOne(); });
}
private static int OnePlusOne()
{ return 1+1; }
And my main method:
static void Main(string[] args)
{
Pluck.Work();
}
I am missing something because I toggle a breakpoint within OnePlusOne
and never gets hit.
Task.WhenAll(tasks)
is an async
method and so returns a Task
. You need to await
that task to make sure you proceed only after all the tasks completed. Currently your application may end before these tasks get a chance to run.
This results in marking Work
with the async
keyword and have it return a Task
itself:
internal static async Task WorkAsync()
{
Task[] tasks = new Task[5];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = SumAsync();
}
await Task.WhenAll(tasks);
}
Since you can't use await
in Main
you need to synchronously wait with Wait
:
static void Main(string[] args)
{
Pluck.WorkAsync().Wait();
}
In cases where a single await
is the last things you do in a method (as in your SumAsync
and my WorkAsync
) you can remove it and the async
keyword and simply return the task instead. This slightly improves performance. More about it here .
Note: You should only block on a task with Wait
in very specific cases (like inside Main
) since it can lead to deadlocks. A better solution would be to use an AsyncContext
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.