异步等待-优点是什么



下面的代码示例是从文件中读取。它是有效的,但有人能解释等待的好处吗?我的意思是,代码无论如何都会"等待"文件读取返回结果,那么使用wait会有什么变化呢?我可以在这个例子中添加一些内容,以更好地说明等待的目的吗?

using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
}
static async void CallMethod()
{
string filePath = "C:\Temp\sampleFile.txt";
Task<int> task = ReadFile(filePath);
Console.WriteLine("BEFORE");
int length = await task;
Console.WriteLine(" Total length: " + length);
}
static async Task<int> ReadFile(string file)
{
int length = 0;
Console.WriteLine("File reading is starting");
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;
}
}

异步代码在等待I/O请求完成(对文件系统或网络等的请求(时不会锁定当前线程。

你在这里做的事情说明了你的优势:

Task<int> task = ReadFile(filePath);
Console.WriteLine("BEFORE");
int length = await task;

您正在开始读取文件,但在等待文件系统的响应时,您可以执行其他操作,例如写入控制台。

Microsoft有一系列写得很好的文章,介绍使用async和await进行异步编程。通读一遍。

关于您的代码的其他一些注释:您应该避免使用async void。它不允许您知道任务何时完成(或者如果完成(。因此,你的task.Wait()实际上并没有做任何有用的事情。

从C#7.1开始,您也可以使Main方法异步,并使用await CallMethod()而不是创建任务的3行。

最新更新