C# 异步转同步 TaskCompletionSource
本文通过TaskCompletionSource,实现异步转同步
首先有一个异步方法,如下异步任务延时2秒后,返回一个结果
1 private static async Task<string> TestWithResultAsync()2 {3 Debug.WriteLine("1. 异步任务start……");4 await Task.Delay(2000);5 Debug.WriteLine("2. 异步任务end……");6 return "2秒以后";7 }
如何使用TaskCompletionSource将此异步方法转成同步呢?
1 private void TaskCompleteSourceButton_OnClick(object sender, RoutedEventArgs e)2 {3 var result = AwaitByTaskCompleteSource(TestWithResultAsync);4 Debug.WriteLine($"4. TaskCompleteSource_OnClick end:{result}");5 }
TaskCompletionSource使用步骤:
- 获取var sourceTask =TaskCompletionSource.Task,
- 等待此sourceTask结果-sourceTask.Result
- 设置设置sourceTask.Result的结果值
1 private string AwaitByTaskCompleteSource(Func<Task<string>> func) 2 { 3 var taskCompletionSource = new TaskCompletionSource<string>(); 4 var task1 = taskCompletionSource.Task; 5 Task.Run(async () => 6 { 7 var result = await func.Invoke(); 8 taskCompletionSource.SetResult(result); 9 });10 var task1Result = task1.Result;11 Debug.WriteLine($"3. AwaitByTaskCompleteSource end:{task1Result}");12 return task1Result;13 }
测试结果:
关键字:异步转同步,TaskCompletionSource
参考资料:
赞 (0)