C# 异步转同步 TaskCompletionSource

本文通过taskcompletionsource,实现异步转同步

首先有一个异步方法,如下异步任务延时2秒后,返回一个结果

private static async task<string> testwithresultasync()
{
debug.writeline("1. 异步任务start……");
await task.delay(2000);
debug.writeline("2. 异步任务end……");
return "2秒以后";
}

  

如何使用taskcompletionsource将此异步方法转成同步呢?

private void taskcompletesourcebutton_onclick(object sender, routedeventargs e)
{
      var result = awaitbytaskcompletesource(testwithresultasync);
      debug.writeline($"4. taskcompletesource_onclick end:{result}");
}

  

taskcompletionsource使用步骤:

  1. 获取var sourcetask =taskcompletionsource.task,
  2. 等待此sourcetask结果-sourcetask.result
  3. 设置设置sourcetask.result的结果值
private void taskcompletesourcebutton_onclick(object sender, routedeventargs e)
{
      var result = awaitbytaskcompletesource(testwithresultasync);
      debug.writeline($"4. taskcompletesource_onclick end:{result}");
}

 

 

 

 

posted @ 2021-08-27 09:52  静下心来邹  阅读(417)  评论(0编辑  收藏  举报