C# 中的Async 和 Await 方法的实际应用
注意 Method 3需要一个参数,即Method 1的返回类型。在这里,await关键字对于等待Method 1任务的完成起着至关重要的作用。
static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; callMethod(); Console.WriteLine("callMethod"); Console.ReadKey(); } public static async void callMethod() { Task<int> task = Method1(); Method2(); int count = await task; // 后面的代码阻塞,直到 Method1 执行完 Method3(count); } public static async Task<int> Method1() { int count = 0; var t= Task.Run(() => // 开始异步 { for (int i = 0; i < 25; i++) { Thread.Sleep(10); Console.WriteLine(" Method 1"); count += 1; } }); await t; // 主线程继续,没有 await ,主线程会继续阻塞 return count; } public static async void Method2() { await Task.Run(()=> { for (int i = 0; i < 25; i++) { Thread.Sleep(10); Console.WriteLine(" Method 2"); } }); } public static void Method3(int count) { Console.WriteLine("Total count is " + count); }
在扫描一段文本内容之后,需要执行一段逻辑。最后等待读取的内容长度。这里就实际应用了异步的思想
class Program { static void Main() { Task task = new Task(CallMethod); task.Start(); task.Wait(); Console.ReadLine(); } static async void CallMethod() { string filePath = "E:\\sampleFile.txt"; Task<int> task = ReadFile(filePath); Console.WriteLine(" Other Work 1"); Console.WriteLine(" Other Work 2"); Console.WriteLine(" Other Work 3"); int length = await task; Console.WriteLine(" Total length: " + length); Console.WriteLine(" After work 1"); Console.WriteLine(" After work 2"); } static async Task<int> ReadFile(string file) { int length = 0; Console.WriteLine(" File reading is stating"); using (StreamReader reader = new StreamReader(file)) { // Reads all characters from the current position to the end of the stream asynchronously // and returns them as one string. string s = await reader.ReadToEndAsync(); length = s.Length; } Console.WriteLine(" File reading is completed"); return length; } }