C# 异步转同步 PushFrame

Posted kybs0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 异步转同步 PushFrame相关的知识,希望对你有一定的参考价值。

异步转同步-PushFrame

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

首先有一个异步方法,如下异步任务延时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     

在UI线程执行此任务,尝试转化为同步

1     private void PushFrameTaskResult_OnClick(object sender, RoutedEventArgs e)
2     
3         var result = AwaitByPushFrame(TestWithResultAsync());
4         Debug.WriteLine($"PushFrameTaskResult_OnClick end:result");
5     

PushFrame异步转同步的实现:

 1     public static TResult AwaitByPushFrame<TResult>(Task<TResult> task)
 2     
 3         var frame = new DispatcherFrame();
 4         task.ContinueWith(t =>
 5         
 6             frame.Continue = false;
 7         );
 8         Dispatcher.PushFrame(frame);
 9         return task.Result;
10     

测试结果:

技术图片

 

Task不带返回值的处理:

1     public static void AwaitByPushFrame(Task task)
2     
3         var frame = new DispatcherFrame();
4         task.ContinueWith(t =>
5         
6             frame.Continue = false;
7         );
8         Dispatcher.PushFrame(frame);
9     

 PushFrame的缺陷

PS:pushFrame虽然能够实现异步转同步,但也有缺陷,可以选择性的使用

技术图片

 

PushFrame的详细原理及缺陷,可参考小伙伴水先生的《 深入了解 WPF Dispatcher 的工作原理(PushFrame 部分)

以上是关于C# 异步转同步 PushFrame的主要内容,如果未能解决你的问题,请参考以下文章

Dubbo异步转同步

C# 同步调用 异步调用 异步回调 多线程的作用

IOS简单的异步转同步操作

同步异步的概念(ajax是异步,C#是同步)

实现异步转同步

同步和异步(转)