Welcome

首页 / 软件开发 / .NET编程技术 / .NET相关问题:使用WebClient执行异步I/O

.NET相关问题:使用WebClient执行异步I/O2011-11-14 msdn Stephen Toub问:我非常喜欢 System.IO.File 类上用于读取和写入数据的静态帮助程序方法:ReadAllText、 ReadAllBytes、WriteAllText、WriteAllBytes 等等。但是,这些方法都是同步的,我希望能够异步使用 它们,让它们也异步使用 I/O。我知道 System.IO.FileStream 类支持异步 I/O;那 System.IO.File 呢 ?

答:System.IO.File 的方法仅支持同步操作。但是用于实施您所述的异步方法的功能肯定是存 在的。在本专栏中,我将详细介绍用于实现此目标的两种方法,首先是其中一个更复杂但更有效的方法。

首先,我定义实际想要实现的 API。您引用的原始签名如下所示:

public static byte [] ReadAllBytes(string path);public static string ReadAllText(string path);public static void WriteAllBytes(string path, byte [] bytes);public static void WriteAllText(string path, string contents);
我想要它们的异步版本 ,并将它们定义为:

public static void ReadAllBytesAsync(  string path, Action<byte[]> success, Action<Exception> failure);public static void ReadAllTextAsync(  string path, Action<string> success, Action<Exception> failure);public static void WriteAllBytesAsync(  string path, byte[] bytes,  Action success, Action<Exception> failure);public static void WriteAllTextAsync(  string path, string contents,  Action success, Action<Exception> failure);
这些签名与原件非常类似。Read* 方法不是同步返回数据,而是接受两个委托,一个用于成功执行一个用于异常执行,其中前者传递读取数 据,而后者传递所有产生的异常。Write* 方法也接受两个委托,但 success 委托没有参数,因为并无预 期的输出(原始 Write* 方法返回 void)。