简体   繁体   English

从头开始异步处理

[英]Async processing from scratch

I have the following class which is named Pluck: 我有以下名为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. 我错过了一些东西,因为我在OnePlusOne切换了一个断点而从未被击中。

Task.WhenAll(tasks) is an async method and so returns a Task . Task.WhenAll(tasks)是一个async方法,因此返回Task You need to await that task to make sure you proceed only after all the tasks completed. 您需要await该任务,以确保仅在所有任务完成后才继续操作。 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: 这导致使用async关键字标记“ Work ,并使其返回一个Task本身:

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 : 由于您无法在Main使用await ,因此需要与Wait同步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. 如果在方法中最后要做一次await (如SumAsync和我的WorkAsync ),则可以将其和async关键字删除,而只需返回任务即可。 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. 注意:仅在非常特殊的情况下(例如Main ),才应使用Wait阻止任务,因为它可能导致死锁。 A better solution would be to use an AsyncContext . 更好的解决方案是使用AsyncContext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM