非同期の戻り値の型 (C# および Visual Basic)

単一のメソッドには、3 とおりの戻り値の型があります: Task<TResult>、および無効 Task。Visual Basic では、無効の戻り値の型は [サブ] のプロシージャとして書き込まれます。async の方法の詳細については、Async および Await を使用した非同期プログラミング (C# および Visual Basic)を参照してください。

それぞれの戻り値の型は、次のセクションの 1 つがにチェックされ、トピックの最後で 3 種類のすべてを使用する完全な例を検索できます。

[!メモ]

例を実行するには、Visual Studio 2012 Visual Studio には、Windows のデスクトップの 2012 を表します。、またはのコンピューターに .NET Framework 4.5 がインストールされている必要があります。

このトピックは、次のセクションで構成されています。

  • タスク (T) 戻り値の型
  • 戻り値の型には。
  • 無効の戻り値の型
  • コード例全体
  • 関連トピック

タスク (T) 戻り値の型

Task<TResult> の戻り値の型は、オペランドに型 TResultがある [Return] (Visual Basic) または (返します。、C) ステートメントを含む非同期のメソッドに使用されます。

次の例では、TaskOfT_MethodAsync の非同期のメソッドは整数を返す return ステートメントが含まれます。したがって、メソッドの申告は、Visual Basic で Task(Of Integer) または、C で Task<int> の戻り値の型を指定する必要があります。

' TASK(OF T) EXAMPLE
Async Function TaskOfT_MethodAsync() As Task(Of Integer)

    ' The body of an async method is expected to contain an awaited 
    ' asynchronous call.
    ' Task.FromResult is a placeholder for actual work that returns a string.
    Dim today As String = Await Task.FromResult(Of String)(DateTime.Now.DayOfWeek.ToString())

    ' The method then can process the result in some way.
    Dim leisureHours As Integer
    If today.First() = "S" Then
        leisureHours = 16
    Else
        leisureHours = 5
    End If

    ' Because the return statement specifies an operand of type Integer, the 
    ' method must have a return type of Task(Of Integer). 
    Return leisureHours
End Function
// TASK<T> EXAMPLE
async Task<int> TaskOfT_MethodAsync()
{
    // The body of the method is expected to contain an awaited asynchronous
    // call.
    // Task.FromResult is a placeholder for actual work that returns a string.
    var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());

    // The method then can process the result in some way.
    int leisureHours;
    if (today.First() == 'S')
        leisureHours = 16;
    else
        leisureHours = 5;

    // Because the return statement specifies an operand of type int, the
    // method must have a return type of Task<int>.
    return leisureHours;
}

TaskOfT_MethodAsync が期待の式内から呼び出されると、予想の式は TaskOfT_MethodAsyncから返されるタスクに格納されている整数値 (leisureHoursの値) を取得します。詳細については、に関する式を待機します Await 演算子 (Visual Basic)await (C# リファレンス)を参照してください。

次のコードは TaskOfT_MethodAsyncメソッドを呼び出し、待機します。結果は result1 の変数に再配置。

' Call and await the Task(Of T)-returning async method in the same statement.
Dim result1 As Integer = Await TaskOfT_MethodAsync()
// Call and await the Task<T>-returning async method in the same statement.
int result1 = await TaskOfT_MethodAsync();

次のコードに示すように、このしくみ TaskOfT_MethodAsync に Await または awaitまたはアプリケーションからの呼び出しを区切ることによって発生するかを理解できます。メソッドの申告の場合と同様に、Task(Of Integer) すぐに必要な取得または Task<int>しないメソッドの呼び出し TaskOfT_MethodAsync。タスクは、この例の integerTask の変数に再配置。integerTask が Task<TResult>であるため、型 TResultの Result のプロパティが含まれています。この場合、TResult が整数型を表します。Await か await が integerTaskに適用すると、予期の式は integerTaskの Result のプロパティの内容になります。値は result2 の変数に再配置。

Caution メモ注意

Result のプロパティは、ブロックのプロパティです。タスクが終了する前にアクセスしようとすると、現在アクティブなスレッドはタスクが完了する値を使用するまでブロックします。ほとんどの場合、Await か await を使用してプロパティを直接アクセスする代わりに値にアクセスする必要があります。

' Call and await in separate statements.
Dim integerTask As Task(Of Integer) = TaskOfT_MethodAsync()

' You can do other work that does not rely on resultTask before awaiting.
textBox1.Text &= String.Format("Application can continue working while the Task(Of T) runs. . . . " & vbCrLf)

Dim result2 As Integer = Await integerTask
// Call and await in separate statements.
Task<int> integerTask = TaskOfT_MethodAsync();

// You can do other work that does not rely on integerTask before awaiting.
textBox1.Text += String.Format("Application can continue working while the Task<T> runs. . . . \r\n");

int result2 = await integerTask;

次のコードは、ステートメントの表示 result1 の変数、result2 の変数と Result のプロパティの値が同じであることを確認します。タスクが予期される前に Result のプロパティがブロックのプロパティで、アクセスしないことに注意してください。

' Display the values of the result1 variable, the result2 variable, and
' the resultTask.Result property.
textBox1.Text &= String.Format(vbCrLf & "Value of result1 variable:   {0}" & vbCrLf, result1)
textBox1.Text &= String.Format("Value of result2 variable:   {0}" & vbCrLf, result2)
textBox1.Text &= String.Format("Value of resultTask.Result:  {0}" & vbCrLf, integerTask.Result)
// Display the values of the result1 variable, the result2 variable, and
// the integerTask.Result property.
textBox1.Text += String.Format("\r\nValue of result1 variable:   {0}\r\n", result1);
textBox1.Text += String.Format("Value of result2 variable:   {0}\r\n", result2);
textBox1.Text += String.Format("Value of integerTask.Result: {0}\r\n", integerTask.Result);

戻り値の型には。

return ステートメントが含まれていない場合、またはオペランドを返さない return ステートメントを含む単一のメソッドは、通常 Taskの戻り値の型があります。このようなメソッドは、同期的に実行する書き込まれたらメソッド (Visual Basic の[サブ] のプロシージャ) を返す無効です。非同期のメソッドに Task の戻り値の型を使用した場合、呼び出し元のメソッドが呼び出された async のメソッドが終了するまで呼び出し元の完了を中断するには、目的の演算子を使用できます。

次の例では、非同期のメソッド Task_MethodAsync は、return ステートメントが含まれていません。したがって、待たれる必要 Task_MethodAsync を有効にするメソッドに対して Task の戻り値の型を指定します。Task の型のシグネチャに戻り値を格納するには Result のプロパティは含まれません。

' TASK EXAMPLE
Async Function Task_MethodAsync() As Task

    ' The body of an async method is expected to contain an awaited 
    ' asynchronous call.
    ' Task.Delay is a placeholder for actual work.
    Await Task.Delay(2000)
    textBox1.Text &= String.Format(vbCrLf & "Sorry for the delay. . . ." & vbCrLf)

    ' This method has no return statement, so its return type is Task. 
End Function
// TASK EXAMPLE
async Task Task_MethodAsync()
{
    // The body of an async method is expected to contain an awaited 
    // asynchronous call.
    // Task.Delay is a placeholder for actual work.
    await Task.Delay(2000);
    // Task.Delay delays the following line by two seconds.
    textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");

    // This method has no return statement, so its return type is Task.  
}

Task_MethodAsync は呼び出し元のステートメントと同様に予想の式の代わりに予想のステートメントを同期 Sub に使用するか、無効メソッドを返すことによって呼び出され、待たれます。要求の演算子のアプリケーションはこの場合は値を生成しません。

次のコードは Task_MethodAsyncメソッドを呼び出し、待機します。

' Call and await the Task-returning async method in the same statement.
Await Task_MethodAsync()
// Call and await the Task-returning async method in the same statement.
await Task_MethodAsync();

Task<TResult> の前の例のように、次のコードに示すように、演算子のアプリケーションから Task_MethodAsync に呼び出しを分離することができます。ただし Task に Result のプロパティがないこと、期待演算子が Taskに適用されるときに値を作り出されないことを記憶します。

次のコードは Task_MethodAsync が返すタスクの要求から Task_MethodAsync を呼び出すことができます。

' Call and await in separate statements.
Dim simpleTask As Task = Task_MethodAsync()

' You can do other work that does not rely on simpleTask before awaiting.
textBox1.Text &= String.Format(vbCrLf & "Application can continue working while the Task runs. . . ." & vbCrLf)

Await simpleTask
// Call and await in separate statements.
Task simpleTask = Task_MethodAsync();

// You can do other work that does not rely on simpleTask before awaiting.
textBox1.Text += String.Format("\r\nApplication can continue working while the Task runs. . . .\r\n");

await simpleTask;

無効の戻り値の型

無効の戻り値の型 (Visual Basic のSub のプロシージャ) の主な用途は、戻り値の型を無効にするイベント ハンドラーに要求されます。または無効の戻り値が "- " -" に忘れやすくするために使用できるアクティビティを実行するメソッドに対して無効返すメソッドまたはメソッドをオーバーライドするために使用できます。ただし無効返す非同期のメソッドが待機することはできないため、できる限り Task を返す必要があります。このようなメソッドの呼び出し元が完了までに呼び出される非同期のメソッドを待たずに完了に引き続き呼び出し元は非同期のメソッドが生成される値または例外とは無関係である必要があります。

無効返す非同期のメソッド呼び出し元はメソッドからスローされる、このような未処理の例外により一般に発生してアプリケーションが発生する例外をキャッチできないします。例外が TaskTask<TResult>またはを返す非同期のメソッドにあった場合は、例外が再スロー返されたタスクおよびタスクが待たれるときに格納されます。したがって、例外を生成できる非同期のメソッドが Task または Task<TResult> の戻り値の型を持つメソッドの呼び出しが、待たれことを確認します。

非同期のメソッドの例外をキャッチする方法の詳細については、try-catch (C# リファレンス)Try...Catch...Finally ステートメント (Visual Basic)を参照してください。

次のコードは、非同期のイベント ハンドラーを定義します。

' SUB EXAMPLE
Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click

    textBox1.Clear()

    ' Start the process and await its completion. DriverAsync is a 
    ' Task-returning async method.
    Await DriverAsync()

    ' Say goodbye.
    textBox1.Text &= vbCrLf & "All done, exiting button-click event handler."
End Sub
// VOID EXAMPLE
private async void button1_Click(object sender, RoutedEventArgs e)
{
    textBox1.Clear();

    // Start the process and await its completion. DriverAsync is a 
    // Task-returning async method.
    await DriverAsync();

    // Say goodbye.
    textBox1.Text += "\r\nAll done, exiting button-click event handler.";
}

コード例全体

Windows Presentation Foundation (WPF) の次のプロジェクトでは、このトピックのコード例を示します。

プロジェクトを実行するには、次の手順を実行します:

  1. Visual Studio を起動します。

  2. メニュー バーで [ファイル][新規][プロジェクト] の順にクリックします。

    [新しいプロジェクト] ダイアログ ボックスが表示されます。

  3. [インストール済み] では、[テンプレート] のカテゴリは、[Visual Basic][Visual C#] を選択し、[ウィンドウ] を選択します。プロジェクトの種類の一覧 [WPF アプリケーション] を選択します。

  4. AsyncReturnTypes にプロジェクトの名前として" "と入力し、[OK] のボタンをクリックします。

    ソリューション エクスプローラーに新しいプロジェクトが表示されます。

  5. Visual Studio では、エディターを選択します [MainWindow.xaml] のタブを参照してください。

    タブが表示されない場合は、[ソリューション エクスプローラー] で MainWindow.xaml のショートカット メニューを開き、[開く] を選択します。

  6. MainWindow.xaml の [XAML] のペインで、次のコードに置き換えます。

    <Window x:Class="MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button x:Name="button1" Content="Start" HorizontalAlignment="Left" Margin="214,28,0,0" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Center" FontWeight="Bold" FontFamily="Aharoni" Click="button1_Click"/>
            <TextBox x:Name="textBox1" Margin="0,80,0,0" TextWrapping="Wrap" FontFamily="Lucida Console"/>
    
        </Grid>
    </Window>
    
    <Window x:Class="AsyncReturnTypes.MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button x:Name="button1" Content="Start" HorizontalAlignment="Left" Margin="214,28,0,0" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Center" FontWeight="Bold" FontFamily="Aharoni" Click="button1_Click"/>
            <TextBox x:Name="textBox1" Margin="0,80,0,0" TextWrapping="Wrap" FontFamily="Lucida Console"/>
    
        </Grid>
    </Window>
    

    テキスト ボックスとボタンを含む簡単なウィンドウは、MainWindow.xaml の [デザイン] のペインに表示されます。

  7. [ソリューション エクスプローラー] では、MainWindow.xaml.cs のショートカット メニューを開き、[コードの表示] を選択します。

  8. 次のコードで MainWindow.xaml.cs のコードに置き換えます。

    Class MainWindow
    
        ' SUB EXAMPLE
        Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click
    
            textBox1.Clear()
    
            ' Start the process and await its completion. DriverAsync is a 
            ' Task-returning async method.
            Await DriverAsync()
    
            ' Say goodbye.
            textBox1.Text &= vbCrLf & "All done, exiting button-click event handler."
        End Sub
    
    
        Async Function DriverAsync() As Task
    
            ' Task(Of T) 
            ' Call and await the Task(Of T)-returning async method in the same statement.
            Dim result1 As Integer = Await TaskOfT_MethodAsync()
    
            ' Call and await in separate statements.
            Dim integerTask As Task(Of Integer) = TaskOfT_MethodAsync()
    
            ' You can do other work that does not rely on resultTask before awaiting.
            textBox1.Text &= String.Format("Application can continue working while the Task(Of T) runs. . . . " & vbCrLf)
    
            Dim result2 As Integer = Await integerTask
    
            ' Display the values of the result1 variable, the result2 variable, and
            ' the resultTask.Result property.
            textBox1.Text &= String.Format(vbCrLf & "Value of result1 variable:   {0}" & vbCrLf, result1)
            textBox1.Text &= String.Format("Value of result2 variable:   {0}" & vbCrLf, result2)
            textBox1.Text &= String.Format("Value of resultTask.Result:  {0}" & vbCrLf, integerTask.Result)
    
            ' Task 
            ' Call and await the Task-returning async method in the same statement.
            Await Task_MethodAsync()
    
            ' Call and await in separate statements.
            Dim simpleTask As Task = Task_MethodAsync()
    
            ' You can do other work that does not rely on simpleTask before awaiting.
            textBox1.Text &= String.Format(vbCrLf & "Application can continue working while the Task runs. . . ." & vbCrLf)
    
            Await simpleTask
        End Function
    
    
        ' TASK(OF T) EXAMPLE
        Async Function TaskOfT_MethodAsync() As Task(Of Integer)
    
            ' The body of an async method is expected to contain an awaited 
            ' asynchronous call.
            ' Task.FromResult is a placeholder for actual work that returns a string.
            Dim today As String = Await Task.FromResult(Of String)(DateTime.Now.DayOfWeek.ToString())
    
            ' The method then can process the result in some way.
            Dim leisureHours As Integer
            If today.First() = "S" Then
                leisureHours = 16
            Else
                leisureHours = 5
            End If
    
            ' Because the return statement specifies an operand of type Integer, the 
            ' method must have a return type of Task(Of Integer). 
            Return leisureHours
        End Function
    
    
        ' TASK EXAMPLE
        Async Function Task_MethodAsync() As Task
    
            ' The body of an async method is expected to contain an awaited 
            ' asynchronous call.
            ' Task.Delay is a placeholder for actual work.
            Await Task.Delay(2000)
            textBox1.Text &= String.Format(vbCrLf & "Sorry for the delay. . . ." & vbCrLf)
    
            ' This method has no return statement, so its return type is Task. 
        End Function
    
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace AsyncReturnTypes
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            // VOID EXAMPLE
            private async void button1_Click(object sender, RoutedEventArgs e)
            {
                textBox1.Clear();
    
                // Start the process and await its completion. DriverAsync is a 
                // Task-returning async method.
                await DriverAsync();
    
                // Say goodbye.
                textBox1.Text += "\r\nAll done, exiting button-click event handler.";
            }
    
            async Task DriverAsync()
            {
                // Task<T> 
                // Call and await the Task<T>-returning async method in the same statement.
                int result1 = await TaskOfT_MethodAsync();
    
                // Call and await in separate statements.
                Task<int> integerTask = TaskOfT_MethodAsync();
    
                // You can do other work that does not rely on integerTask before awaiting.
                textBox1.Text += String.Format("Application can continue working while the Task<T> runs. . . . \r\n");
    
                int result2 = await integerTask;
    
                // Display the values of the result1 variable, the result2 variable, and
                // the integerTask.Result property.
                textBox1.Text += String.Format("\r\nValue of result1 variable:   {0}\r\n", result1);
                textBox1.Text += String.Format("Value of result2 variable:   {0}\r\n", result2);
                textBox1.Text += String.Format("Value of integerTask.Result: {0}\r\n", integerTask.Result);
    
                // Task
                // Call and await the Task-returning async method in the same statement.
                await Task_MethodAsync();
    
                // Call and await in separate statements.
                Task simpleTask = Task_MethodAsync();
    
                // You can do other work that does not rely on simpleTask before awaiting.
                textBox1.Text += String.Format("\r\nApplication can continue working while the Task runs. . . .\r\n");
    
                await simpleTask;
            }
    
            // TASK<T> EXAMPLE
            async Task<int> TaskOfT_MethodAsync()
            {
                // The body of the method is expected to contain an awaited asynchronous
                // call.
                // Task.FromResult is a placeholder for actual work that returns a string.
                var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());
    
                // The method then can process the result in some way.
                int leisureHours;
                if (today.First() == 'S')
                    leisureHours = 16;
                else
                    leisureHours = 5;
    
                // Because the return statement specifies an operand of type int, the
                // method must have a return type of Task<int>.
                return leisureHours;
            }
    
    
            // TASK EXAMPLE
            async Task Task_MethodAsync()
            {
                // The body of an async method is expected to contain an awaited 
                // asynchronous call.
                // Task.Delay is a placeholder for actual work.
                await Task.Delay(2000);
                // Task.Delay delays the following line by two seconds.
                textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");
    
                // This method has no return statement, so its return type is Task.  
            }
        }
    }
    
  9. プログラムを実行するには、F5 キーを選択し、を [開始] のボタンをクリックします。

    次の出力が表示されます。

    Application can continue working while the Task<T> runs. . . . 
    
    Value of result1 variable:   5
    Value of result2 variable:   5
    Value of integerTask.Result: 5
    
    Sorry for the delay. . . .
    
    Application can continue working while the Task runs. . . .
    
    Sorry for the delay. . . .
    
    All done, exiting button-click event handler.
    

参照

処理手順

チュートリアル: Async と Await を使用した Web へのアクセス (C# および Visual Basic)

チュートリアル: 非同期メソッドと共にデバッガーを使用する

関連項目

async (C# リファレンス)

Async (Visual Basic)

Await 演算子 (Visual Basic)

await (C# リファレンス)

FromResult<TResult>

概念

非同期プログラムにおける制御フロー (C# および Visual Basic)