异步/等待-什么时候返回Task vs void?

本文翻译自:async/await - when to return a Task vs void?

Under what scenarios would one want to use 在什么情况下您想使用

public async Task AsyncMethod(int num)

instead of 代替

public async void AsyncMethod(int num)

The only scenario that I can think of is if you need the task to be able to track its progress. 我能想到的唯一情况是您是否需要任务以跟踪其进度。

Additionally, in the following method, are the async and await keywords unnecessary? 另外,在以下方法中,async和await关键字是否不必要?

public static async void AsyncMethod2(int num)
{
    await Task.Factory.StartNew(() => Thread.Sleep(num));
}

#1楼

参考:https://stackoom.com/question/oxED/异步-等待-什么时候返回Task-vs-void


#2楼

1) Normally, you would want to return a Task . 1)通常,您需要返回Task The main exception should be when you need to have a void return type (for events). 主要的例外应该是当您需要具有void返回类型(用于事件)时。 If there's no reason to disallow having the caller await your task, why disallow it? 如果没有理由不允许呼叫者await您的任务,为什么要拒​​绝它呢?

2) async methods that return void are special in another aspect: they represent top-level async operations , and have additional rules that come into play when your task returns an exception. 2)返回void async方法在另一方面是特殊的:它们代表顶级异步操作 ,并且在您的任务返回异常时会发挥作用。 The easiest way is to show the difference is with an example: 最简单的方法是通过一个示例来显示差异:

static async void f()
{
    await h();
}

static async Task g()
{
    await h();
}

static async Task h()
{
    throw new NotImplementedException();
}

private void button1_Click(object sender, EventArgs e)
{
    f();
}

private void button2_Click(object sender, EventArgs e)
{
    g();
}

private void button3_Click(object sender, EventArgs e)
{
    GC.Collect();
}

f 's exception is always "observed". f的例外始终是“观察到”。 An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. 留下顶级异步方法的异常就像其他未处理的异常一样被对待。 g 's exception is

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值