异步操作使您能在不阻塞主线程的情况下执行占用大量资源的 I/O 操作。
从 .NET Framework 4.5 开始,I/O 类型包括异步方法来简化异步操作。 异步方法在其名称中包括 Async 。 这些异步方法基于流类(例如 Stream、 FileStream和 MemoryStream)和用来向流中读出或写入数据的类(例如 TextReader 和 TextWriter)实现。
在 .NET Framework 4 和更早的版本中,您必须使用 BeginRead 和 EndRead 之类的方法来实现异步 I/O 操作。 这些方法仍然在 .NET Framework 4.5 中可用,从而支持传统的代码;但是,异步方法能帮助你更轻松地实现异步 I/O 操作。
如下面的示例所示,若要实现异步 I/O 操作,请把这些关键字和异步方法结合使用:
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string StartDirectory = @"c:\Users\exampleuser\start";
string EndDirectory = @"c:\Users\exampleuser\end";
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
}
}
使用异步方法以流的形式打开文件并读取其内容。
namespace ExampleApplication
{
public sealed partial class BlankPage : Page
{
public BlankPage()
{
this.InitializeComponent();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
StringBuilder contents = new StringBuilder();
string nextLine;
int lineCounter = 1;
var openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".txt");
StorageFile selectedFile = await openPicker.PickSingleFileAsync();
using (StreamReader reader = new StreamReader(await selectedFile.OpenStreamForReadAsync()))
{
while ((nextLine = await reader.ReadLineAsync()) != null)
{
contents.AppendFormat("{0}. ", lineCounter);
contents.Append(nextLine);
contents.AppendLine();
lineCounter++;
if (lineCounter > 3)
{
contents.AppendLine("Only first 3 lines shown.");
break;
}
}
}
DisplayContentsBlock.Text = contents.ToString();
} }}