下面的方法有什么区别吗?其中一个比另一个更可取吗?
public static async Task SendAsync1(string to, string subject, string htmlBody) {
// ...
await smtp.SendMailAsync(message);
// No return statement
}
public static Task SendAsync2(string to, string subject, string htmlBody) {
// ...
return smtp.SendMailAsync(message);
}
该方法将从 MVC 控制器方法调用;例如:
public async Task<ActionResult> RegisterUser(RegisterViewModel model)
{
// ...
await Mailer.SendAsync(user.Email, subject, body);
return View(model);
}
有两个实际差异:
- 第二个选项不会创建允许的状态机机制
async-await
用法。那将会有一个minor对性能的积极影响。
- 异常处理会略有不同。当您将方法标记为
async
任何异常都存储在返回的任务中(来自异步部分和同步部分),并且仅在等待(或等待)任务时抛出。当它不是async
,同步部分的异常行为就像任何其他方法一样。
我的建议:使用第二个可以提高性能,但要注意异常和错误。
显示差异的示例:
public static async Task Test()
{
Task pending = Task.FromResult(true);
try
{
pending = SendAsync1();
}
catch (Exception)
{
Console.WriteLine("1-sync");
}
try
{
await pending;
}
catch (Exception)
{
Console.WriteLine("1-async");
}
pending = Task.FromResult(true);
try
{
pending = SendAsync2();
}
catch (Exception)
{
Console.WriteLine("2-sync");
}
try
{
await pending;
}
catch (Exception)
{
Console.WriteLine("2-async");
}
}
public static async Task SendAsync1()
{
throw new Exception("Sync Exception");
await Task.Delay(10);
}
public static Task SendAsync2()
{
throw new Exception("Sync Exception");
return Task.Delay(10);
}
Output:
1-async
2-sync
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)