码迷,mamicode.com
首页 > Windows程序 > 详细

C# 异步转同步 PushFrame

时间:2019-07-08 00:23:44      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:了解   参考   选择性   lse   herf   alt   bsp   span   event   

异步转同步-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

标签:了解   参考   选择性   lse   herf   alt   bsp   span   event   

原文地址:https://www.cnblogs.com/kybs0/p/11148847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!