c#异步方法返回void和task的区别

如果异步(async关键字)方法有返回值,返回类型为t时,返回类型必然是 task<t>。

但是如果没有返回值,异步方法的返回类型有2种,一个是返回 task, 一个是返回 void:

 public async task countdownasync(int count)
 {
  for (int i = count; i >= 0; i--)
  {
   await task.delay(1000); 
  }
 }

 public async void countdown(int count)
 {
  for (int i = count; i >= 0; i--)
  {
   await task.delay(1000);
  }
 }

调用时,如果返回 task, 但返回值被忽略时,vs 会用绿色波浪线警告:

 countdownasync(3);
 ~~~~~~~~~~~~~~~~~

信息为:

(awaitable) task asyncexample.countdownasync(int count)

usage:
 await countdownasync(…);

because this call is not awaited, execution of the current method continues before the call is completed. consider applying the ‘await’ operator to the result of the call.

中文为:

cs4014:由于此调用不会等待,因此在此调用完成之前将会继续执行当前方法。请考虑将”await”运算符应用于调用结果。

添加 await 后就正常了:

 await countdownasync(3);

如果调用者不是一个异步方法,因为只有在异步方法中才可以使用 await,

或者并不想在此等待,如想同时执行多个 countdownasync(),

就不能应用 await 来消除警告。

此时可以改用 void 返回值的版本:

void test()
{
 ...
 countdown(3);
 countdown(3);
 ...
}

async void countdown(int count)
{
 for (int i = count; i >= 0; i--)
 {
  await task.delay(1000);
 }
}

never call async task methods without also awaiting on the returned task. if you don’t want to wait for the async behaviour to complete, you should call an async void method instead.

摘自:http://www.stevevermeulen.com/index.php/2017/09/using-async-await-in-unity3d-2017/

countdown() 可以直接调用 countdownasync() 实现:

async void countdown(int count)
{
 await countdownasync(count);
}

使用下划线变量忽略异步方法的返回值也可以消除警告:

void test()
{
 ...
 _ = countdownasync(3);
 _ = countdownasync(3);
 ...
}

但是这样同时也会忽略 countdownasync() 中的异常。如以下异常会被忽略。

void test()
{
 ...
 _ = countdownasync(3);
 ...
}

async task countdownasync(int count)
{
 for (int i = count; i >= 0; i--)
 {
  await task.delay(1000); 
 }
 throw new exception();
}

如果是调用返回 void 的异步方法,unity 会报错:

exception: exception of type ‘system.exception’ was thrown.

对 async 后缀的说明

you could say that the async suffix convention is to communicate to the api user that the method is awaitable. for a method to be awaitable, it must return task for a void, or task<t> for a value-returning method, which means only the latter can be suffixed with async.

摘自:https://stackoverflow.com/questions/15951774

grpc 生成的代码中,异步请求返回了一个 asynccall 对象,asynccall 实现了 getawaiter() 接口:

  public virtual grpc::asyncunarycall<global::routeguide.feature> getfeatureasync(global::routeguide.point request, ...)

可以这样调用并等待:

 var resp = await client.getfeatureasync(req);

虽然返回类型不是task<>, 但是可等待,所以添加了 async 后缀。

总结

到此这篇关于c#异步方法返回void与task区别的文章就介绍到这了,更多相关c#异步方法返回区别内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!