C#における非同期処理 -Taskクラスとasync/await-

https://i-msdn.sec.s-msft.com/dynimg/IC612215.png

Async および Await を使用した非同期プログラミング (C# および Visual Basic)

※並列処理(Parallelクラス、Parallel LINQ)は別

  • 基本形
// The following line creates and starts the task.
var myTask = someWebAccessMethodAsync(url);

// While the task is running, you can do other work that doesn't depend
// on the results of the task.
// . . . . .

// The application of await suspends the rest of this method until the task is complete.
var result = await myTask;
  • 非同期タスク開始から結果取得までに他のタスクが不要の場合(当然返り値は Task ではなく、その完了時に取得できる値)
string result = await someWebAccessMethodAsync(url);
  • 複数の Web 要求を並列実行
private async Task CreateMultipleTasksAsync()
{
    // Declare an HttpClient object, and increase the buffer size. The
    // default buffer size is 65,536.
    HttpClient client =
        new HttpClient() { MaxResponseContentBufferSize = 1000000 };

    // Create and start the tasks. As each task finishes, DisplayResults 
    // displays its length.
    Task<int> download1 = 
        ProcessURLAsync("http://msdn.microsoft.com", client);
    Task<int> download2 = 
        ProcessURLAsync("http://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client);
    Task<int> download3 = 
        ProcessURLAsync("http://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client);

    // Await each task.
    int length1 = await download1;
    int length2 = await download2;
    int length3 = await download3;

    int total = length1 + length2 + length3;

    // Display the total count for the downloaded websites.
    resultsTextBox.Text +=
        string.Format("\r\n\r\nTotal bytes returned:  {0}\r\n", total);
}