filestream

FileStream的异步操作怎样实现

小樊
89
2024-07-01 21:37:37
栏目: 编程语言

在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关键字,可以在异步操作完成之前让程序继续执行其他操作。这样可以提高程序的并发性能和响应性。

0
看了该问题的人还看了