- [C#] Hướng dẫn fix lỗi Visual Studio 2022 not Support Target Net Framework 4.5.2
- [C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform
- [DATABASE] Hướng dẫn thêm và cập nhật Extended Property Column trong Table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng Vertical Gridview để hiển thị thông tin sản phẩm
- [C#] Hướng dẫn sử dụng Json Schema để Validate chuỗi string có phải json
- [C#] Hướng dẫn sử dụng công cụ Clean Code trên Visual Studio
- [C#] Hướng dẫn Drag and Drop File vào RichTextBox
- [C#] Hướng dẫn tạo hiệu ứng Karaoke Text Effect Winform
- [C#] Sử dụng thư viện ZedGraph vẽ biểu đồ Line, Bar, Pie trên Winform
- [DATABASE] Hướng dẫn sort sắp xếp địa chỉ IP trên sqlserver sử dụng hàm PARSENAME
- [C#] Theo dõi sử kiện process Start hay Stop trên Winform
- [ASP.NET] Chia sẻ source code chụp hình sử dụng camera trên website
- [C#] Chạy ứng dụng trên Virtual Desktop (màn hình ảo) Winform
- [C#] Mã hóa và giải mã Data Protection API trên winform
- [C#] Hướng dẫn tạo Gradient Background trên Winform
- [DATABASE] Hướng dẫn convert Epoch to DateTime trong sqlserver
- [DATABASE] Hướng dẫn sử dụng STRING_AGG và CONCAT_WS trong sqlserver 2017
- [C#] Hướng dẫn Copy With All Property in Class Object
- [DEVEXPRESS] Hướng dẫn load Json DataSource vào GridView
- [C#] Hướng dẫn tạo chữ ký trên winform Signature Pad
[C#] Sử dụng từ khóa Async và Await trong lập trình csharp
Bài viết này, mình sẽ hướng dẫn sử dụng từ khóa Aysnc và await trong C#, thông qua bài ví dụ: đếm số ký tự trong file.
- Giao diện demo của chương trình:
Giao diện có hình như trên, sau khi chúng ta click vào nút process File thì chương trình sẽ đếm tổng số ký tự trong file Text VD: file text ở thư mục C:DATAdata.txt
Trường hợp 1: Code xử lý nút nhấn process file đồng bộ (Synchronous C#)
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AsyncExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int CountCharacters()
{
int count = 0;
// Create a StreamReader and point it to the file to read
using (StreamReader reader = new StreamReader("C:DataData.txt"))
{
string content = reader.ReadToEnd();
count = content.Length;
// Make the program look busy for 5 seconds
Thread.Sleep(5000);
}
return count;
}
private void btnProcessFIle_Click(object sender, EventArgs e)
{
lblCount.Text = "Processing file. Please wait...";
int count = CountCharacters();
lblCount.Text = count.ToString() + " characters in file";
}
}
}
Lưu ý: với đoạn code chạy đồng bộ như trên, thì khi chúng ta click vào nút process file.
1. Chương trình sẽ bị treo.
2. Chúng ta không thể di chuyển hay thao tác được ứng dụng.
+ Và đây là cách sử dụng từ khóa Async và Await sẽ giúp chúng ta giải quyết được vấn đề này.
// Make the method async by using the async keyword
private async void btnProcessFIle_Click(object sender, EventArgs e)
{
// Create a task to execute CountCharacters() function
// CountCharacters() function returns int, so we created Task
Task task = new Task(CountCharacters);
task.Start();
lblCount.Text = "Processing file. Please wait...";
// Wait until the long running task completes
int count = await task;
lblCount.Text = count.ToString() + " characters in file";
}
- Sau khi, chạy bằng phương thức này, ứng dụng của bạn sẽ không còn bị treo, hay ứng dụng có thể di chuyển một cách dễ dàng.
Have Fun :)
Theo http://csharp-video-tutorials.blogspot.com