c# の 非同期処理( async /await )を Task で待つ

● task.Wait() で待つ

非同期ではないメソッドから 非同期メソッドを呼ぶ場合は次のようにします。

var task = accessor.GetResponseAsync("http://hatenablog.com/");
task.Wait();

● ConfiguredTaskAwaitable..GetAwaiter().GetResult() で待つ

メソッドが ConfiguredTaskAwaitable を返す時は、次のようにして待ちます。

var taskAwaitable = client.SendEmailAsync(msg).ConfigureAwait(false);
taskAwaitable.GetAwaiter().GetResult();

● そもそも非同期処理の戻り値を受け取るには

public async Task<int> MyMethodAsync( int id )
{
    ..........
}

としておいて、

int result = await MyMethodAsync( 123456 );

とします。

参考 : https://blog.xin9le.net/entry/2012/07/30/123150

● task.Result の取得で待つ

var task = accessor.GetResponseAsync("http://hatenablog.com/");
string result = task.Result;

引用: https://hiroronn.hatenablog.jp/entry/20171005/1507207811

No.1754
07/21 16:32

edit