Csharp xử lý đa luồng
Lớp Parallel thuộc namespace
ParallelLoopResult result = Parallel.For(i1, i2, task); Vòng lặp chạy (biến chạy) từ số nguyên
Action Ví dụ: Source Code class Program { //In thông tin, Task ID và thread ID đang chạy public static void PintInfo(string info) => Console.WriteLine($"{info, 10} task:{Task.CurrentId,3} " + $"thread: {Thread.CurrentThread.ManagedThreadId}"); // Phương thức phù hợp với Action Từ kết quả trên bạn thấy:
Để ý, bản thân vòng lặp Điều này, lại dẫn đến Source Code public static async void RunTask(int i) { PintInfo($"Start {i,3}"); // Task.Delay(1000).Wait(); // Task dừng 1s - rồi mới chạy tiếp await Task.Delay(1); // Task.Delay là một async nên có thể await, RunTask chuyển điểm gọi nó tại đây PintInfo($"Finish {i,3}"); } Kết quả khi chạy, vòng lặp Với ParallelLoopResult result = Parallel.ForEach(source, RunTask); Trong đó Source Code public static async void RunTask(string s) { PintInfo($"Start {s,10}"); await Task.Delay(1); // Task.Delay là một async nên có thể await, RunTask chuyển điểm gọi nó tại đây PintInfo($"Finish {s,10}"); } public static void ParallelFor() { string[] source = new string[] {"xuanthulab1","xuanthulab2","xuanthulab3", "xuanthulab4","xuanthulab5","xuanthulab6", "xuanthulab7","xuanthulab8","xuanthulab9"}; // Dùng List thì khởi tạo // List Với các vòng lặp ở trên, thì các tác vụ định nghĩa trọng một Action, nhưng nếu muốn chạy song song nhiều loại Action (phương thức) một lúc thì dùng Parallel.Invoke(action1, action2, action3); Trong đó tham số là các Source Code public static void PintInfo(string info) => Console.WriteLine($"{info, 10} task:{Task.CurrentId,3} " + $"thread: {Thread.CurrentThread.ManagedThreadId}"); public static async void RunTask(string s) { PintInfo($"Start {s,10}"); await Task.Delay(1); PintInfo($"Finish {s,10}"); } public static void actionA() { PintInfo($"Finish {"ActionA",10}"); } public static void actionB() { PintInfo($"Finish {"ActionB",10}"); } public static void ParallelInvoke() { Action action1 = () => { RunTask("Action1"); }; Parallel.Invoke(action1, actionA, actionB); } static void Main(string[] args) { ParallelInvoke(); Console.WriteLine("Press any key ..."); Console.ReadKey(); } Tham khảo các mã nguồn CS028_Parallelhoặc tải về ex028 |