これは、次のようにasync キーワードとawait キーワードを使用して実行できます。
// Since this method is an async method, it will return as
// soon as it hits an await statement.
public async void MyMethod()
{
// ... other code ...
HttpClient client = new HttpClient();
// Using the async keyword, anything within this method
// will wait until after client.GetAsync returns.
HttpResponseMessage responseMsg = await client.GetAsync(requesturl).Result;
responseMsg.EnsureSuccessStatusCode();
Task<string> responseBody = responseMsg.Content.ReadAsStringAsync();
// ... other code ...
}
await キーワードはスレッドをブロックしないことに注意してください。代わりに、非同期メソッドの残りがキューに入れられた後、制御が呼び出し元に返され、処理を続行できるようになります。MyMethod()
の呼び出し元も client.GetAsync() が完了するまで待機する必要がある場合は、同期呼び出しを使用することをお勧めします。