使用异步操作可以执行资源密集型的I/O操作,而不会阻塞主线程。 在 Windows 8.x 应用商店应用或桌面应用中,这种性能注意事项尤其重要,其中耗时的流作可能会阻止 UI 线程,并使你的应用看起来好像不起作用一样。
从 .NET Framework 4.5 开始,I/O 类型包括异步方法,以简化异步作。 异步方法Async
在其名称中包含,例如ReadAsync,、WriteAsync、CopyToAsyncFlushAsync、ReadLineAsync和ReadToEndAsync。 这些异步方法在流类(例如 Stream、FileStream 和 MemoryStream)以及用于从流读取或写入流的类(例如 TextReader 和 TextWriter)上实现。
在 .NET Framework 4 及更早版本中,必须使用诸如 BeginRead 和 EndRead 实现异步 I/O作等方法。 这些方法在当前 .NET 版本中仍可用以支持旧代码;但是,异步方法可帮助你更轻松地实现异步 I/O作。
C# 和 Visual Basic 都有两个用于异步编程的关键字:
Async
(Visual Basic) 或async
(C#) 修饰符,用于标记包含异步作的方法。Await
(Visual Basic) 或await
(C#) 运算符,该运算符应用于异步方法的结果。
若要实现异步 I/O作,请将这些关键字与异步方法结合使用,如以下示例所示。 有关详细信息,请参阅使用 async 和 await 的异步编程(C#)或使用 Async 和 Await 进行异步编程(Visual Basic)。
以下示例演示如何使用两个 FileStream 对象将文件从一个目录异步复制到另一个目录。 请注意, Click 控件的 Button 事件处理程序使用 async
修饰符进行标记,因为它调用异步方法。
using System;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
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(Path.Combine(endDirectory, Path.GetFileName(filename))))
{
await sourceStream.CopyToAsync(destinationStream);
}
}
}
}
}
}
Imports System.IO
Class MainWindow
Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim StartDirectory As String = "c:\Users\exampleuser\start"
Dim EndDirectory As String = "c:\Users\exampleuser\end"
For Each filename As String In Directory.EnumerateFiles(StartDirectory)
Using SourceStream As FileStream = File.Open(filename, FileMode.Open)
Using DestinationStream As FileStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf("\"c)))
Await SourceStream.CopyToAsync(DestinationStream)
End Using
End Using
Next
End Sub
End Class
下一个示例类似于上一个示例,但使用 StreamReader 和 StreamWriter 对象以异步方式读取和写入文本文件的内容。
private async void Button_Click(object sender, RoutedEventArgs e)
{
string UserDirectory = @"c:\Users\exampleuser\";
using (StreamReader SourceReader = File.OpenText(UserDirectory + "BigFile.txt"))
{
using (StreamWriter DestinationWriter = File.CreateText(UserDirectory + "CopiedFile.txt"))
{
await CopyFilesAsync(SourceReader, DestinationWriter);
}
}
}
public async Task CopyFilesAsync(StreamReader Source, StreamWriter Destination)
{
char[] buffer = new char[0x1000];
int numRead;
while ((numRead = await Source.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
await Destination.WriteAsync(buffer, 0, numRead);
}
}
Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim UserDirectory As String = "c:\Users\exampleuser\"
Using SourceReader As StreamReader = File.OpenText(UserDirectory + "BigFile.txt")
Using DestinationWriter As StreamWriter = File.CreateText(UserDirectory + "CopiedFile.txt")
Await CopyFilesAsync(SourceReader, DestinationWriter)
End Using
End Using
End Sub
Public Async Function CopyFilesAsync(Source As StreamReader, Destination As StreamWriter) As Task
Dim buffer(4095) As Char
Dim numRead As Integer
numRead = Await Source.ReadAsync(buffer, 0, buffer.Length)
Do While numRead <> 0
Await Destination.WriteAsync(buffer, 0, numRead)
numRead = Await Source.ReadAsync(buffer, 0, buffer.Length)
Loop
End Function
下一个示例展示了代码隐藏文件和 XAML 文件,这些文件用于在 Windows 8.x Store 应用中将文件以 Stream 的形式打开,并通过使用 StreamReader 类的实例来读取其内容。 它使用异步方法以流的形式打开文件并读取其内容。
using System;
using System.IO;
using System.Text;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
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();
}
}
}
Imports System.Text
Imports System.IO
Imports Windows.Storage.Pickers
Imports Windows.Storage
NotInheritable Public Class BlankPage
Inherits Page
Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
Dim contents As StringBuilder = New StringBuilder()
Dim nextLine As String
Dim lineCounter As Integer = 1
Dim openPicker = New FileOpenPicker()
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
openPicker.FileTypeFilter.Add(".txt")
Dim selectedFile As StorageFile = Await openPicker.PickSingleFileAsync()
Using reader As StreamReader = New StreamReader(Await selectedFile.OpenStreamForReadAsync())
nextLine = Await reader.ReadLineAsync()
While (nextLine <> Nothing)
contents.AppendFormat("{0}. ", lineCounter)
contents.Append(nextLine)
contents.AppendLine()
lineCounter = lineCounter + 1
If (lineCounter > 3) Then
contents.AppendLine("Only first 3 lines shown.")
Exit While
End If
nextLine = Await reader.ReadLineAsync()
End While
End Using
DisplayContentsBlock.Text = contents.ToString()
End Sub
End Class
<Page
x:Class="ExampleApplication.BlankPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ExampleApplication"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel Background="{StaticResource ApplicationPageBackgroundBrush}" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="Display lines from a file."></TextBlock>
<Button Content="Load File" Click="Button_Click_1"></Button>
<TextBlock Name="DisplayContentsBlock"></TextBlock>
</StackPanel>
</Page>