异步转同步-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 部分)》