C# 同步转异步 TaskCompletionSource

当我们遇到一些异步执行又无法等待时的逻辑,比如动画的执行。

而业务上又需要等待逻辑的完成,再去处理后续的操作。这时需要转成异步方法

如下,同步执行一个动画后,再输出日志:

1     private async void TaskCompleteSourceAwait_OnClick(object sender, RoutedEventArgs e)
2     {
3         bool isCompleted = await AwaitByTaskCompletionAsync(new Storyboard() { Duration = new Duration(TimeSpan.FromSeconds(2)) });
4         Debug.WriteLine($"TaskCompleteSourceAwait_OnClick end:{isCompleted}");
5     }

通过TaskCompletionSource如何转化为异步方法,并等待动画完成?

 1     /// <summary>
 2     /// 执行动画
 3     /// </summary>
 4     /// <param name="storyboard"></param>
 5     /// <returns></returns>
 6     public static async Task<bool> AwaitByTaskCompletionAsync(Storyboard storyboard)
 7     {
 8         var taskCompletionSource = new TaskCompletionSource<bool>();
 9 
10         Debug.WriteLine("Storyboard start");
11 
12         storyboard.Completed += OnStoryboardCompleted;
13         storyboard.Begin();
14 
15         void OnStoryboardCompleted(object sender, EventArgs e)
16         {
17             Debug.WriteLine("Storyboard end");
18             storyboard.Completed -= OnStoryboardCompleted;
19             taskCompletionSource.SetResult(true);
20         }
21         return await taskCompletionSource.Task;
22     }

测试效果:

 

参考资料:

posted @ 2019-07-07 23:55  唐宋元明清2188  阅读(...)  评论(... 编辑 收藏