非同期メソッドをawaitする場合、.Resultする場合、Taskで受ける場合の処理順比較 | 主にDIYのブログ

主にDIYのブログ

ブログの説明を入力しません。

自分用メモ。

 

private async void btn_Click(object sender, EventArgs e)
{
    Console.WriteLine("1");
    bool a = await subasync();
    Console.WriteLine("4");
}

private async Task<bool> subasync()
{
    Console.WriteLine("2");
    Console.WriteLine("一旦メッセージループへ戻り");
    await Task.Delay(3000);
    Console.WriteLine("3秒経ったら");
    Console.WriteLine("3");
    return true;
}

 


private void btn_Click(object sender, EventArgs e)
{
    Console.WriteLine("1");
    bool a = subasync().Result;
    Console.WriteLine("4");
}

private async Task<bool> subasync()
{
    Console.WriteLine("2");
    Console.WriteLine("一旦固まり終了を待つ ConfigureAwait(false)が無ければフリーズ");
    await Task.Delay(3000).ConfigureAwait(false);
    Console.WriteLine("3秒経ったら");
    Console.WriteLine("3");
    return true;
}


Task<bool> tsk;
private void btn_Click(object sender, EventArgs e)
{
    Console.WriteLine("1");
    tsk = subasync();
    Console.WriteLine("3秒待たずに");
    Console.WriteLine("3");

    Console.WriteLine("ここで待たずにreturnするならTask終了をContinueWithで受けるべき");

    Console.WriteLine("一旦固まり終了を待つ ConfigureAwait(false)が無ければフリーズ");
    //tsk.Wait();
    bool rslt = tsk.Result;

    Console.WriteLine("5");
    Console.WriteLine("メッセージループに戻る");
}

private async Task<bool> subasync()
{
    Console.WriteLine("2");
    await Task.Delay(3000).ConfigureAwait(false);
    Console.WriteLine("3秒経ったら");
    Console.WriteLine("4");
    return true;
}