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的詳細原理及缺陷,可參考小伙伴walterlv的《 深入了解 WPF Dispatcher 的工作原理(PushFrame 部分)

 

參考資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM