WPF異步模式簡單應用方式介紹
WPF異步模式是一個比較復雜的實現過程。不過我們在這篇文章中將會為大家介紹一下有關WPF異步模式簡單的實現方法,方便大家理解。#t#
以WeatherForecast為例. 需求: 用戶在窗體上點擊一個按鈕, 程序去網絡上查詢天氣情況, 并把結果顯示在窗體上. 網絡查詢是一個耗時任務, 在等待結果的同時, 用戶將看到一個旋轉的時鐘動畫表示程序正在查詢.
WPF異步模式為:
窗口類MainWindow中有耗時函數: string FetchWeatherFromInternet().
窗口類MainWindow中包含一個函數 UpdateUIWhenWeatherFetched(string result), 用于把任務結果顯示在界面上.
當用戶點擊按鈕時, 在 btnFetchWeather_Click() 中,
如果是同步調用, 代碼很簡單, 如下:
- string result = this.
FetchWeatherFromInternet();- this.UpdateUserInterface( result );
現在需要異步執(zhí)行, 稍微麻煩點, 需要用到3個delegate, 其中一個代表要執(zhí)行的任務, 另一個代表任務結束后的callback, 還有一個代表交給UI執(zhí)行的任務, 上述WPF異步模式代碼被替換成如下:
- // 代表要執(zhí)行的異步任務
- Func<string> asyncAction =
this.FetchWeatherFromInternet();- // 處理異步任務的結果
- Action<IAsyncResult> resultHandler =
delegate( IAsyncResult asyncResult )- {
- //獲得異步任務的返回值, 這段代碼必須
在UI線程中執(zhí)行- string weather = asyncAction.
EndInvoke( asyncResult );- this.UpdateUIWhenWeatherFetched
( weather );- };
- //代表異步任務完成后的callback
- AsyncCallback asyncActionCallback =
delegate( IAsyncResult asyncResult )- {
- this.Dispatcher.BeginInvoke
( DispatcherPriority.Background,
resultHandler, asyncResult );- };
- //這是才開始執(zhí)行異步任務
- asyncAction.BeginInvoke
( asyncActionCallback, null );- private void ForecastButtonHandler
(object sender, RoutedEventArgs e)- {
- this.UpdateUIWhenStartFetching
Weather();- //異步任務封裝在一個delegate中,
此delegate將運行在后臺線程- Func<string> asyncAction = this.
FetchWeatherFromInternet;- //在UI線程中得到異步任務的返回值,
并更新UI //必須在UI線程中執(zhí)行 Action
<IAsyncResult> resultHandler =
delegate(IAsyncResult asyncResult)
{ string weather = asyncAction.EndInvoke
(asyncResult); this.UpdateUIWhenWeather
Fetched(weather); };- //異步任務執(zhí)行完畢后的callback, 此callback
運行在后臺線程上. //此callback會異步調用
resultHandler來處理異步任務的返回值.- AsyncCallback asyncActionCallback =
delegate(IAsyncResult asyncResult)- {
- this.Dispatcher.BeginInvoke
(DispatcherPriority.Background,
resultHandler, asyncResult);- };
- //在UI線程中開始異步任務, //asyncAction
(后臺線程), asyncActionCallback(后臺線程)
和resultHandler(UI線程) //將被依次執(zhí)行- asyncAction.BeginInvoke(asyncAction
Callback, null);- }
- private string FetchWeatherFromInternet()
- {
- // Simulate the delay from network access.
- Thread.Sleep(4000);
- String weather = "rainy";
- return weather;
- }
- private void UpdateUIWhenStartFetching
Weather()- {
- // Change the status this.fetchButton.
IsEnabled = false;- this.weatherText.Text = "";
- }
- private void UpdateUIWhenWeatherFetched
(string weather)- {
- //Update UI text
- this.fetchButton.IsEnabled = true;
- this.weatherText.Text = weather;
- }
以上就是對WPF異步模式實現的簡單方法介紹。