演示如何使用async 和await 關(guān)鍵字實(shí)現(xiàn)異步操作,不阻塞UI。
在UI創(chuàng)建一個(gè)Button事件和一個(gè)Label實(shí)現(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>
后臺(tái)代碼:
using System.IO;
using System.Threading;
該函數(shù)模擬實(shí)現(xiàn)耗時(shí)的操作
private int countCharacters()
? ? ? ? {
? ? ? ? ? ? int count = 0;
? ? ? ? ? ? using(StreamReader reader= new StreamReader("data.txt"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? string content = reader.ReadToEnd();
? ? ? ? ? ? ? ? count = content.Length;
? ? ? ? ? ? ? ? Thread.Sleep(3000); // 等待3秒模擬耗時(shí)
? ? ? ? ? ? }
? ? ? ? ? ? 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";
? ? ? ? }
此時(shí)UI會(huì)阻塞,在執(zhí)行的3秒中,UI是阻塞的,無(wú)法拖動(dòng)UI的。
使用異步方法,UI不會(huì)再阻塞的,可以再執(zhí)行計(jì)算函數(shù),UI不再阻塞,可以拖動(dòng)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";
? ? ? ? }