2
1

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 3 years have passed since last update.

同期メソッドから非同期メソッドを呼び出す

Posted at

いろいろあって非同期にできないメソッドから非同期メソッドを呼び出す必要があって、単純に Task.Wait()したらスレッドがデッドロックした。解決するためには?

呼び出される方

public class BarModel{
  public int Id {get; set;}
  public string Name {get; set;}
}
public class FooService{
  public async Task<BarModel> GetBarAsync(){
    // ... ここで ToListAsync()とかやる
  }
}

呼び出す方

public class Program{
  public static void Main(){
    var service = new FooService();
    
    var model = Task.Run(()=>{
      return service.GetBarAsync();
    }).GetAwaiter().GetResult();    
  }
}

呼び出しを Task.Run() で囲み、 GetAwaiter().GetResult() とする。

正しいかな?

2
1
4

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?