在异步方法中返回和等待任务之间的区别 [英] Difference between returning and awaiting a Task in an async method

查看:17
本文介绍了在异步方法中返回和等待任务之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的方法有什么区别吗?一个比另一个更可取吗?

Is there any difference between the methods below? Is one preferable over the other?

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控制器方法调用;例如:

This method will be called from MVC controller methods; for example:

public async Task<ActionResult> RegisterUser(RegisterViewModel model)
{
  // ...
  await Mailer.SendAsync(user.Email, subject, body);
  return View(model);
}

推荐答案

有两个实际差异:

  1. 第二个选项不会创建允许 async-await 使用的状态机机制.这将对性能产生轻微的积极影响.
  2. 异常处理会有所不同.当您将方法标记为 async 时,任何异常都存储在返回的任务中(来自异步部分和同步部分),并且仅在等待(或等待)任务时才会抛出.当它不是 async 时,同步部分的异常就像在任何其他方法中一样.
  1. The second option will not create the state machine mecanism that allows for async-await usage. That will have a minor positive effect on performance.
  2. The exception handling would be a little different. When you mark a method as async any exceptions are stored in the returned task (both from the asynchronous part and the synchronous one) and thrown only when the task is awaited (or waited). When it's not async, the exceptions from the synchronous parts act just like in any other method.

我的建议:使用第二个来增加性能提升,但要注意异常和错误.

My suggestion: Use the second one for the added performance boost but keep an eye out for exceptions and bugs.

显示差异的示例:

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);
}

输出:

1-async
2-sync

这篇关于在异步方法中返回和等待任务之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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