当我们遇到一些异步执行又无法等待时的逻辑,比如动画的执行。
而业务上又需要等待逻辑的完成,再去处理后续的操作。这时需要转成异步方法
如下,同步执行一个动画后,再输出日志:
private async void TaskCompleteSourceAwait_OnClick(object sender, RoutedEventArgs e)
{
bool isCompleted = await AwaitByTaskCompletionAsync(new Storyboard() { Duration = new Duration(TimeSpan.FromSeconds()) });
Debug.WriteLine($"TaskCompleteSourceAwait_OnClick end:{isCompleted}");
}
通过TaskCompletionSource如何转化为异步方法,并等待动画完成?
/// <summary>
/// 执行动画
/// </summary>
/// <param name="storyboard"></param>
/// <returns></returns>
public static async Task<bool> AwaitByTaskCompletionAsync(Storyboard storyboard)
{
var taskCompletionSource = new TaskCompletionSource<bool>(); Debug.WriteLine("Storyboard start"); storyboard.Completed += OnStoryboardCompleted;
storyboard.Begin(); void OnStoryboardCompleted(object sender, EventArgs e)
{
Debug.WriteLine("Storyboard end");
storyboard.Completed -= OnStoryboardCompleted;
taskCompletionSource.SetResult(true);
}
return await taskCompletionSource.Task;
}
测试效果:
参考资料: