The difference between returning and waiting for a task in an asynchronous method

Is there any difference between the methods below? Preferred than another?

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

This method will be called from MVC controller methods; eg:

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

There are 2 practical differences:

  • The second option will not create a state-saving mechanism that allows you to use it async-await. This will have a slight positive effect on performance.
  • . 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);
}

:

1-async
2-sync
+5

, await , the await , , .

, ( ), .

, async ,

+4

, , . "async" SendAsync2.

, , , . , async/wait.

, , , . , , :

async Task<X> Get() 
{
     using (something) 
     {
          return await GetX();
     }
}

:

Task<X> Get() 
{
    using (something)
    {
        return GetX(); 
    }
}

using , x, something , . , , something Entity Framework.

return await try .

+4

Source: https://habr.com/ru/post/1543781/


All Articles