本文翻译自: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