实现异步文件输入和输出
文件输入和输出作对于许多应用程序至关重要,允许它们读取和写入硬盘驱动器上的文件。 在 C# 中,可以同步或异步执行文件输入和输出(文件 I/O)。 异步文件 I/O 对于提高应用程序性能和响应能力特别有用,尤其是在文件作可能需要大量时间(例如读取大型文件或将数据写入硬盘驱动器)的情况下。
创建用于读取和写入文件的异步方法
async和await是 C# 中的关键字,使用它们可以创建异步方法,这些方法可以执行文件 I/O 操作而不会阻塞主线程。 这在具有用户界面的应用程序中特别有用,其中阻止主线程可能会导致冻结或无响应的 UI。
System.IO 和 System.Text.Json 命名空间提供了用于异步执行文件 I/O 操作的类和方法。
例如, File 命名空间中的 System.IO 类提供异步读取和写入文件的方法。 该方法 File.ReadAllTextAsync 以异步方式读取文件的内容,而 File.WriteAllTextAsync 该方法以异步方式将文本写入文件。 这些方法返回一个 Task<string> 或 Task 表示异步作,允许你使用 await 关键字等待其完成,而不会阻止调用线程。
在命名空间中 System.Text.Json ,该 JsonSerializer 类提供用于序列化和反序列化 JSON 数据的异步方法。 该方法 JsonSerializer.SerializeAsync 以异步方式将对象序列化为 JSON 字符串,而 JsonSerializer.DeserializeAsync 该方法以异步方式将 JSON 字符串反序列化为对象。 这些方法还返回一个 Task,用于表示异步操作。
下面的代码示例演示如何创建异步方法,以序列化 C# 对象、将 JSON 字符串写入文件、将文件内容读入字符串,并将 JSON 字符串反序列化回 C# 对象:
using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
public class Account
{
public string Name { get; set; }
public decimal Balance { get; set; }
}
public class Program
{
public static async Task Main()
{
// Combine a directory and file name, then create the directory if it doesn't exist
string directoryPath = @"C:\TempDir";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string fileName = "account.json";
string filePath = Path.Combine(directoryPath, fileName);
Account account = new Account { Name = "Elize Harmsen", Balance = 1000.00m };
// Save account data to a file asynchronously
await SaveAccountDataAsync(filePath, account);
// Load account data from the file asynchronously
Account loadedAccount = await LoadAccountDataAsync(filePath);
Console.WriteLine($"Name: {loadedAccount.Name}, Balance: {loadedAccount.Balance}");
}
public static async Task SaveAccountDataAsync(string filePath, Account account)
{
string jsonString = JsonSerializer.Serialize(account);
await File.WriteAllTextAsync(filePath, jsonString);
}
public static async Task<Account> LoadAccountDataAsync(string filePath)
{
string jsonString = await File.ReadAllTextAsync(filePath);
return JsonSerializer.Deserialize<Account>(jsonString);
}
}
在此示例中,该方法 SaveAccountDataAsync 将对象 Account 序列化为 JSON 字符串,并将其异步写入文件。 该 LoadAccountDataAsync 方法异步地从文件中读取 JSON 字符串,并将其反序列化为 Account 对象。 该方法 Main 演示如何使用 await 关键字调用这些异步方法。
这使应用程序在执行文件I/O操作时无需阻塞主线程,从而提高性能和响应能力。
Directory.CreateDirectory此方法用于创建目录(如果不存在),确保文件可以成功写入。
概要
在本单元中,你学习了如何在 C# 中实现异步文件输入和输出作。 你探讨了如何使用 async 和 await 关键字来创建用于异步读取和写入文件的方法。 通过使用这些技术,可以在执行文件 I/O作时提高应用程序的性能和响应能力。
要点
- 可以在 C# 中同步或异步执行文件输入和输出作。
- 异步文件 I/O 可提高应用程序性能和响应能力。
- 这些
async和await关键字用于创建异步方法以进行文件 I/O操作。 -
System.IO和System.Text.Json命名空间提供了用于异步执行文件 I/O 操作的类和方法。 - 在提供的示例中使用
File类和JsonSerializer类来演示异步文件 I/O 操作。