只是希望有人可以在使用 async 时清除返回类型和 await在 C# 中。我知道您有三种返回类型 Task<T> , Task和 void .
从尝试了解这个我已经读到你应该只使用 void在特殊情况下(事件处理程序)并且如果您正在将同步方法更改为 async方法那么你应该改变一个void Task 的关键字.
我的问题是我需要 Task 吗?返回类型,即使代码是完全独立的并且结果对于继续来说无关紧要?比方说我使用异步方法将一些信息推送到 Web 服务。
我创建了一个小例子来帮助解释:
private void CallingMethod()
{
AsyncMethod();
AsyncTaskMethod(); // any difference between doing these? (not exc handling)
var task = AsyncTaskMethod(); // should I do anything with this task
// before I continue? Or is it simply
// just to show the user that it's async??
// continue with unrelated code that doesnt require task or any code from above
}
private async void AsyncMethod() // is void okay?
{
await LongRunningMethod();
// do other stuff
}
private async Task AsyncTaskMethod() // or should it be Task?
{
await LongRunningMethod();
// do other stuff
}
private async Task LongRunningMethod()
{
// do long running code
}
我的应用程序有很多这样的方法:
private void BigMethod()
{
DoStuff();
DoMoreStuff();
AsyncMethod(); // is this right? Or should I have the task declaration too?
UnrelatedStuff();
}
private async Task AsyncMethod() // should this return task?
{
var result = await GetUserId();
if (result == null)
return;
MyUserId = result;
}
private async Task<int> GetUserId()
{
// do long running code
return 1;
}
如果不清楚,请务必说出来,我会尽量整理一下。谢谢大家。
编辑:
private void CallingMethod()
{
AsyncMethod();
}
private async void AsyncMethod()
{
await LongRunningMethod();
}
private async Task LongRunningMethod()
{
await Task.Run(() =>
{
Thread.Sleep(4000);
});
MessageBox.Show("Done!");
}
针对第一条评论,以上CallingMethod()不使用 async/await 并且在没有锁定 UI 线程的情况下愉快地休眠 4 秒,然后弹出消息框。有什么问题?
请您参考如下方法:
您不必使用Task当方法返回 void 时, 但它确实是首选,原因如下:
返回
Task的异步方法(或Task<T>)将他们的异常(exception)放在返回的Task上,因此调用方法可以检查(当它们认为合适时)是否Task有没有错。Async void方法将它们的异常直接抛出到调用同步上下文中,这使得几乎(几乎因为您仍然可以使用全局异常处理程序,但这对于大型应用程序来说是不可维护的)不可能以确定的方式处理它们的异常.你基本上无法测试任何
async void可能抛出异常的方法async void当方法被调用者运行时,方法被认为是完整的。这会引入很多问题(事实上,当您尝试将现有库转换为异步时,事件处理程序存在很多问题:继续,获取第三方相对复杂的 winforms 库并尝试使您的事件处理程序异步,你'你会看到它造成的破坏!)。没有合理的方法来确定何时
async void方法已经完成(您可以制作自己的SynchronizationContext,但这肯定很复杂)你不能配置
async void调用(不能在其上使用ConfigureAwait),因此延续上下文始终是调用者的同步上下文。
所以...
TL;DR: 不要使用 async void除非你无法避免它(即:使用需要 void 签名的事件处理程序)。这是有原因的。使用 async Task如果您不期望结果。
