2017-07-13 5 views
4

これまでは、WinFormsアプリケーションで同期HttpWebRequest呼び出しを行ってきました。 UIスレッドをブロックしてハングさせないように、非同期に処理を開始したい。したがって、私はHttpClientに切り替えようとしていますが、私は非同期とタスクを初めて使用していて、まだそれを取得していません。非同期のHttpClient応答をWinFormに戻すにはどうすればいいですか?

私はリクエストを開始して応答を取得し、必要なデータ(result、reasonPhrase、headers、code)を分離できますが、textBox1に表示する方法を知ることはできません。また、ex.messageをキャプチャして、タイムアウトまたはメッセージに接続できない場合にフォームに戻る必要があります。

Console.WriteLine()に使用可能な時点で値が書き込まれていますが、表示および処理のために返されたフォームをフォームに戻す必要があります。

namespace AsyncHttpClientTest 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     private void button1_Click(object sender, EventArgs e) 
     { 
      textBox1.Text = "calling Test()...\r\n"; 
      DownloadPageAsync(); 

      // need to get from DownloadPageAsync here: result, reasonPhrase, headers, code 

      textBox1.AppendText("done Test()\r\n"); 
     } 
     static async void DownloadPageAsync() 
     { 
      // ... Use HttpClient. 
      using (HttpClient client = new HttpClient()) 
      { 
       try 
       { 
        using (HttpResponseMessage response = await client.GetAsync(new Uri("http://192.168.2.70/"))) 
        { 
         using (HttpContent content = response.Content) 
         { 
          // need these to return to Form for display 
          string result = await content.ReadAsStringAsync(); 
          string reasonPhrase = response.ReasonPhrase; 
          HttpResponseHeaders headers = response.Headers; 
          HttpStatusCode code = response.StatusCode; 
         } 
        } 
       } 
       catch (Exception ex) 
       { 
        // need to return ex.message for display. 
       } 
      } 
     } 
    } 
} 

どれでも役立つヒントやアドバイス:

ここでは簡単な例ですか?

+4

通話の結果を保存するカスタムクラスを作成します。その後、DownloadPageAsyncからTask を返す – Steve

答えて

6

あなたは

public class DownloadPageAsyncResult { 
    public string result { get; set; } 
    public string reasonPhrase { get; set; } 
    public HttpResponseHeaders headers { get; set; } 
    public HttpStatusCode code { get; set; } 
    public string errorMessage { get; set; } 
} 

async voidメソッドを使用しないでください返すようにしたいデータを保持するためのモデルを作成します。メソッドをasync Taskに変換し、それが許可されているイベントハンドラで呼び出します。

private async void button1_Click(object sender, EventArgs e) { 
    textBox1.Text = "calling Test()...\r\n"; 
    var result = await DownloadPageAsync(); 

    // Access result, reasonPhrase, headers, code here 

    textBox1.AppendText("done Test()\r\n"); 
} 

static HttpClient client = new HttpClient(); 
static async Task<DownloadPageAsyncResult> DownloadPageAsync() { 
    var result = new DownloadPageAsyncResult(); 
    try { 
     using (HttpResponseMessage response = await client.GetAsync(new Uri("http://192.168.2.70/"))) { 
      using (HttpContent content = response.Content) { 
       // need these to return to Form for display 
       string resultString = await content.ReadAsStringAsync(); 
       string reasonPhrase = response.ReasonPhrase; 
       HttpResponseHeaders headers = response.Headers; 
       HttpStatusCode code = response.StatusCode;      

       result.result = resultString; 
       result.reasonPhrase = reasonPhrase; 
       result.headers = headers; 
       result.code = code; 
      } 
     } 
    } catch (Exception ex) { 
     // need to return ex.message for display. 
     result.errorMessage = ex.Message; 
    } 
    return result; 
} 

HttpClientは、ダウンロードが呼び出されるたびに作成されるべきではありません。

What is the overhead of creating a new HttpClient per call in a WebAPI client?

+0

私は(HttpClient ...)を使用していることについて理解しています。私はあなたが正しいと思うし、静的なクライアントを使用するのがこの目的のために最善です。私は同時に(約4件の)リクエストを開始しようと考えていましたが、その気持ちがなくなりました。 – LordChariot

関連する問題