Giống và khác nhau giữa async await và multi thread trong c#
Mọi người cho em hỏi sự giống và khác nhau giữa async await và multi thread trong C# với ạ?
Khi nào thì mình nên dùng async await, khi nào thì mình nên dùng multi thread ạ?
Em cảm ơn ạ.
c#
multithread
asyncawait
Remain: 5
2 Answers
Nguyễn Thái Sơn
Professional
tvd12
Enlightened
tvd12
Enlightened
Hãy nhìn vào chương trình này nhé:
class Program
{
public static void Main(string[] args)
{
Thread.CurrentThread.Name = "main";
Console.WriteLine("Start Thread: " + Thread.CurrentThread.Name);
Hello().GetAwaiter().GetResult();
Console.WriteLine("End Thread: " + Thread.CurrentThread.Name);
Thread.Sleep(100);
}
public static async Task Hello()
{
Console.WriteLine("Current Thread at Start Hello: " + Thread.CurrentThread.Name);
await Task.Run(() =>
{
Thread.CurrentThread.Name = "task";
Console.WriteLine("Current Thread at Task: " + Thread.CurrentThread.Name);
Console.WriteLine("Hello World");
});
Thread.CurrentThread.Name = "async";
Console.WriteLine("Current Thread at End Hello: " + Thread.CurrentThread.Name);
}
}
Và kết quả nó sẽ thế này:
Start Thread: main Current Thread at Start Hello: main Current Thread at Task: task Hello World Current Thread at End Hello: async End Thread: main
Như vậy có nghĩa là việc async await đang diễn ra trên các thread khác nhau, vậy nên theo quan điểm của anh thì trong C# async / await chẳng quan chỉ là 1 cách viết đơn giản hơn cho lập trình multi thread mà thôi.
source code của lớp Task sẽ thấy là nó đang sử dụng kết hợp giữa thread pool và task queue.
source code lớp threadpool anh đang thấy khởi tạo mặc định ban đầu max 32 thread:
private const int INITIAL_SIZE = 32; internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[INITIAL_SIZE]; private volatile int m_mask = INITIAL_SIZE - 1;
-
1