非同期操作を使用すると、メイン スレッドをブロックすることなく、リソースを集中的に使用する I/O 操作を実行できます。 このパフォーマンスの考慮事項は、時間のかかるストリーム操作によって UI スレッドがブロックされ、アプリが動作していないかのように表示される Windows 8.x ストア アプリまたはデスクトップ アプリで特に重要です。
.NET Framework 4.5 以降では、I/O 型には非同期操作を簡略化するための非同期メソッドが含まれています。 非同期メソッドには、Async
、ReadAsync、WriteAsync、CopyToAsync、FlushAsync、ReadLineAsyncなどのReadToEndAsyncが名前に含まれています。 これらの非同期メソッドは、 Stream、 FileStream、 MemoryStreamなどのストリーム クラス、およびストリームの読み取りまたはストリームへの書き込みに使用されるクラス ( TextReader や TextWriterなど) に実装されます。
.NET Framework 4 以前のバージョンでは、 BeginRead や EndRead などのメソッドを使用して非同期 I/O 操作を実装する必要があります。 これらのメソッドは、レガシ コードをサポートするために、現在の .NET バージョンで引き続き使用できます。ただし、非同期メソッドは、非同期 I/O 操作をより簡単に実装するのに役立ちます。
C# と Visual Basic にはそれぞれ、非同期プログラミング用の 2 つのキーワードがあります。
Async
(Visual Basic) またはasync
(C#) 修飾子。非同期操作を含むメソッドをマークするために使用されます。Await
(Visual Basic) またはawait
(C#) 演算子。非同期メソッドの結果に適用されます。
非同期 I/O 操作を実装するには、次の例に示すように、これらのキーワードを非同期メソッドと組み合わせて使用します。 詳細については、「 async および await を使用した非同期プログラミング (C#) 」または 「Async と Await を使用した非同期プログラミング (Visual Basic)」を参照してください。
次の例では、2 つの 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
次の例は、分離コード ファイルと、Windows 8.x ストア アプリでファイルを Stream として開き、 StreamReader クラスのインスタンスを使用してその内容を読み取るために使用される XAML ファイルを示しています。 非同期メソッドを使用して、ファイルをストリームとして開き、その内容を読み取ります。
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>
こちらも参照ください
.NET