好吧,我也有同样的问题。现在解决了。这是一种迟到的建议,但可能对其他人有帮助。
在下面的控制台示例中包含以下 using 语句。
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
Use of the FileStream Class
下面的示例使用 FileStream 类,该类具有导致在操作系统级别发生异步 I/O 的选项。在许多情况下,这将避免阻塞 ThreadPool 线程。要启用此选项,必须在构造函数调用中指定 useAsync=true 或 options=FileOptions.Asynchronous 参数。
如果直接通过指定文件路径打开StreamReader和StreamWriter则没有该选项。如果您向 StreamReader/Writer 提供由 FileStream 类打开的 Stream,则它们确实有此选项。请注意,即使线程池线程被阻塞,异步也会在 UI 应用程序中提供响应能力优势,因为 UI 线程在等待期间不会被阻塞。
书写文字
以下示例将文本写入文件。在每个等待语句处,该方法立即退出。当文件 I/O 完成时,该方法将从await 语句后面的语句处恢复。请注意,async 修饰符位于使用await 语句的方法的定义中。
static void Main(string[] args)
{
ProcessWrite().Wait();
Console.Write("Done ");
Console.ReadKey();
}
static Task ProcessWrite()
{
string filePath = @"c:\temp2\temp2.txt";
string text = "Hello World\r\n";
return WriteTextAsync(filePath, text);
}
static async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}
阅读文字
以下示例从文件中读取文本。文本被缓冲,并且在本例中被放入 StringBuilder 中。与前面的示例不同,await 的计算会生成一个值。 ReadAsync 方法返回一个Task,因此await 的计算会生成一个Int32 值(numRead),该值在操作完成后返回。
static void Main(string[] args)
{
ProcessRead().Wait();
Console.Write("Done ");
Console.ReadKey();
}
static async Task ProcessRead()
{
string filePath = @"c:\temp2\temp2.txt";
if (File.Exists(filePath) == false)
{
Console.WriteLine("file not found: " + filePath);
}
else {
try {
string text = await ReadTextAsync(filePath);
Console.WriteLine(text);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static async Task<string> ReadTextAsync(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();
}
}
原始来源是here http://blogs.msdn.com/b/csharpfaq/archive/2012/01/23/using-async-for-file-access-alan-berman.aspx但不幸的是,该链接现在似乎已失效。
可以找到新的来源here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/using-async-for-file-access.
希望有帮助...