Trong bài này csharpcanban.com sẽ hướng dẫn các bạn một ví dụ đơn giản về việc lập trình bất đồng bộ trong WPF hoặc C#. Lập trình bất đồng bộ luôn gắn liền với 2 từ khóa chủ đạo đó là await và async.

Bước 1: Các bạn hãy tạo mới 1 project cùng với các điều khiển như trên hình
Mã XAML của ứng dụng như sau:
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="253.442,95.395,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<Label Content="Label" Name="lblCount" HorizontalAlignment="Left" Margin="253.442,151.907,0,0" VerticalAlignment="Top" Height="48.983" Width="339.389"/>
</Grid>
</Window>
Bước 2: Thêm các đoạn mã sau vào tệp C#
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int CountCharacters()
{
int count = 0;
// Create a StreamReader and point it to the file to read
using (StreamReader reader = new StreamReader("C:Data.txt"))
{
string content = reader.ReadToEnd();
count = content.Length;
// Đợi 2 giây
Thread.Sleep(2000);
}
return count;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
Task<int> tsk = new Task<int>(CountCharacters);
tsk.Start();
lblCount.Content = "Đang đọc tệp, hãy đợi ...";
int x = await tsk;
lblCount.Content = x.ToString() + " ký tự trong tệp Data.txt";
}
}
}
Bước 3: Thực hiện chạy ứng dụng và chiêm ngưỡng kết quả.
Chúc các bạn thành công.
Hãy tải mã nguồn ở phía dưới