使用异步时/等待着一个控制台应用程序为什么需要AsyncContext? [英] Why is AsyncContext needed when using async/await with a console application?

查看:345
本文介绍了使用异步时/等待着一个控制台应用程序为什么需要AsyncContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话给我的控制台应用程序中的异步方法。我不希望它启动,即前完成awaitable任务后应用短期内退出。好像我可以做到这一点:

I'm calling an async method within my console application. I don't want the app to quit shortly after it starts, i.e. before the awaitable tasks complete. It seems like I can do this:

internal static void Main(string[] args)
{
    try
    {
        Task.WaitAll(DoThisAsync());
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex);
        throw;
    }
}

internal static async Task DoThisAsync()
{
    //...
}

但根据斯蒂芬·克利里的文章好像我不能这样做而应创造某种环境,为异步返回时,它的完成(如 AsyncContext ),以

But according to Stephen Cleary's article it seems like I can't do that and should instead create some kind of context for the async to return to when it's done (e.g. AsyncContext).

在code以上的工作,虽然,之后返回主线程 Task.WaitAll(DoThisAsync()); ,那么为什么我需要使用自定义背景?

The code above works though, and it returns on the main thread after Task.WaitAll(DoThisAsync());, so why do I need to use a custom context?

推荐答案

它不是必需的;这只是我的preference。

It's not required; it's just my preference.

您可以在任务主内同步块(使用等待 / 结果 / 为WaitAll )。语义略有不同;特别是,如果异步code失败,那么等待 / 结果 / 为WaitAll 将包装在异常的 AggregateException ,而 AsyncContext 没有。​​

You can synchronously block on a task within Main (using Wait/Result/WaitAll). The semantics are slightly different; in particular, if the async code fails, then Wait/Result/WaitAll will wrap the exception in an AggregateException, while AsyncContext does not.

此外, AsyncContext 把主线程专门;而不是发送到延续线程池,将他们送回了主线程(默认情况下,你可以随时使用 ConfigureAwait(假)来避免这种情况)。我觉得这是有用的,如果我正在写一个控制台应用程序概念证明,因为 AsyncContext 行为非常相似的用户界面环境。

Also, AsyncContext treats the main thread specially; instead of sending continuations to the thread pool, it will send them back to that main thread (by default; you can always use ConfigureAwait(false) to avoid this). I find this useful if I'm writing a "proof of concept" console app, because AsyncContext behaves very similarly to the UI contexts.

但在一天结束的时候,它只是一个preference的问题。

But at the end of the day, it's just a matter of preference.

这篇关于使用异步时/等待着一个控制台应用程序为什么需要AsyncContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆