0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

async,await,Task<T>,Task

Last updated at Posted at 2022-10-17

同期メソッド

メソッドの中で非同期メソッドを使う

以下のようにする

int Method(){
    var result = Task.Run(()=>{
        // ここで非同期メソッドを呼び出す
        return service.AsyncMethod();
    }).GetAwaiter().GetResult();
    return result;
}

メソッドの中で非同期メソッドを使わない

非同期以前の書き方でよい

int Method(){
        return service.AsyncMethod();
}

非同期メソッド

メソッドの中で非同期メソッドを使う

メソッドを async で修飾し、非同期メソッド呼び出しに await をつける。戻り値は Task<Tresult> か void なら Task とする。

async Task<int> Method(){
    var result = await service.AsyncMethod(); 
    return result;
}

メソッドの中で非同期メソッドを使わない

async にせず、戻り値を Task<TResult> とし、Task.FromResult(value) か Task.CompletedTaskを返す。

Task<int> Method(){
    var result = service.Method(); 
    return Task.FromResult(result);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?