在C#中,可以使用FileStream的異步方法來實現異步操作。以下是一個簡單的示例:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string filePath = "test.txt";
string content = "Hello, world!";
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
byte[] data = Encoding.UTF8.GetBytes(content);
await stream.WriteAsync(data, 0, data.Length);
Console.WriteLine("Write operation completed.");
}
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true))
{
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string readContent = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Read operation completed. Content: {readContent}");
}
}
}
在上面的示例中,我們使用了FileStream的WriteAsync和ReadAsync方法來進行異步寫入和讀取文件的操作。通過使用async和await關鍵字,可以在異步操作完成之前讓程序繼續執行其他操作。這樣可以提高程序的并發性能和響應性。