WPF 使用async await 執(zhí)行異步操作

演示如何使用async 和await 關鍵字實現(xiàn)異步操作,不阻塞UI。

在UI創(chuàng)建一個Button事件和一個Label實現(xiàn)信息的呈現(xiàn)。


XAML碼如下:

<StackPanel>

? ? ? ? ? ? <Button x:Name="btnProcessFile"? Margin="5"

? ? ? ? ? ? ? ? Click="btnProcessFile_Click"

? ? ? ? ? ? ? ? HorizontalAlignment="Center" Width="120" VerticalAlignment="Center" >

? ? ? ? ? ? ? ? Process files

? ? ? ? ? ? </Button>

? ? ? ? ? ? <Label x:Name="lblMsg" Margin="5"></Label>

? ? ? ? </StackPanel>


后臺代碼:

using System.IO;

using System.Threading;


該函數(shù)模擬實現(xiàn)耗時的操作

private int countCharacters()

? ? ? ? {

? ? ? ? ? ? int count = 0;

? ? ? ? ? ? using(StreamReader reader= new StreamReader("data.txt"))

? ? ? ? ? ? {

? ? ? ? ? ? ? ? string content = reader.ReadToEnd();

? ? ? ? ? ? ? ? count = content.Length;

? ? ? ? ? ? ? ? Thread.Sleep(3000); // 等待3秒模擬耗時

? ? ? ? ? ? }

? ? ? ? ? ? return count;

? ? ? ? }


不使用異步方法:

private void btnProcessFile_Click(object sender, RoutedEventArgs e)

? ? ? ? {

? ? ? ? ? ? lblMsg.Content = "Processing File,Please wait....";

? ? ? ? ? ? int count = countCharacters();

? ? ? ? ? ? lblMsg.Content = count.ToString() + " Characters in file";

? ? ? ? }


此時UI會阻塞,在執(zhí)行的3秒中,UI是阻塞的,無法拖動UI的。


使用異步方法,UI不會再阻塞的,可以再執(zhí)行計算函數(shù),UI不再阻塞,可以拖動UI。

private async void btnProcessFile_Click(object sender, RoutedEventArgs e)

? ? ? ? {

? ? ? ? ? ? Task<int> task = new Task<int>(countCharacters);

? ? ? ? ? ? task.Start();

? ? ? ? ? ? lblMsg.Content = "Processing File,Please wait....";

? ? ? ? ? ? int count = await task;//Not Block UI

? ? ? ? ? ? lblMsg.Content = count.ToString() + " Characters in file";

? ? ? ? }

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容