编程语言
首页 > 编程语言> > C# 异步转同步 TaskCompletionSource

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

 

 

 

 

标签:异步,onclick,C#,taskcompletionsource,sourcetask,TaskCompletionSource,result,writel
来源: https://www.cnblogs.com/jxxlz/p/15192546.html