6

asp.net 4.0 アプリケーションに http 要求があります。スレッドが続行する前に待機したいと思います。

HttpClient client = new HttpClient();
HttpResponseMessage responseMsg = client.GetAsync(requesturl).Result;

// I would like to wait till complete.

responseMsg.EnsureSuccessStatusCode();
Task<string> responseBody = responseMsg.Content.ReadAsStringAsync();
4

4 に答える 4

8

responseBody タスクで .Wait() を呼び出す

于 2012-06-11T17:13:02.660 に答える
3

4.5(あなたのタイトルはそう言っています)では、使用できますasync/await

public async void MyMethod()
{
    HttpClient client = new HttpClient();
    HttpResponseMessage responseMsg = await client.GetAsync("http://www.google.com");

    //do your work
}

文字列をダウンロードするには、単に使用できます

public async void Question83()
{
    HttpClient client = new HttpClient();
    var responseStr = await client.GetStringAsync("http://www.google.com");

    MessageBox.Show(responseStr);

}
于 2012-06-11T17:21:20.927 に答える
2

1 つのオプションは .Wait() を呼び出すことですが、より良いオプションは async を使用することです

public async void GetData()
{
    using(HttpClient client = new HttpClient())
    {
        var responseMsg = await client.GetAsync(requesturl);
        responseMsg.EnsureSuccessStatusCode();
        string responseBody = await responseMsg.Content.ReadAsStringAsync();
    }
}

}

于 2012-06-11T17:25:20.423 に答える
1

これは、次のように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() が完了するまで待機する必要がある場合は、同期呼び出しを使用することをお勧めします。

于 2012-06-11T17:33:02.633 に答える