我正在尝试异步读取文件。我想知道这是否是这样做的正确方法。以下是我迄今为止尝试过的。这样对吗?
static void Main(string[] args)
{
Task<string> readFileTask = Task.Run(() => ReadFile(@"C:\Users\User\Desktop\Test.txt"));
readFileTask.Wait();
string astr = readFileTask.Result;
Console.WriteLine(astr);
}
static private async Task<string> ReadFile(string filePath)
{
string text = File.ReadAllText(filePath);
return text;
}
谢谢。
最佳答案
System.IO
提供 File.ReadAllTextAsync
.Net Standard
的方法> 2.1 和 .NET Core
2.0.
如果您使用的是 C# 7.1 或更高版本,您可以使用 File.ReadAllTextAsync
直接在 Main 函数里面。
static async Task Main(string[] args)
{
var astr = await File.ReadAllTextAsync(@"C:\Users\User\Desktop\Test.txt");
Console.WriteLine(astr);
}
不幸的是,如果您没有使用
C# 7.1
或更高,则不能使用 Async
主要的。您必须使用 Task.Run 来调用异步方法。static void Main(string[] args)
{
var astr=Task.Run(async () =>
{
return await File.ReadAllTextAsync(@"C:\Users\User\Desktop\Test.txt");
}).GetAwaiter().GetResult();
Console.WriteLine(astr);
}
如果您正在使用
.NET Framework
那么你必须使用 FileStream
因为 System.IO
不提供File.ReadAllTextAsync
方法。private static async Task<string> ReadAllTextAsync(string filePath)
{
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true))
{
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string text = Encoding.Unicode.GetString(buffer, 0, numRead);
sb.Append(text);
}
return sb.ToString();
}
}
关于c# - 异步读取文件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700704/