これまでは、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.
}
}
}
}
}
どれでも役立つヒントやアドバイス:
ここでは簡単な例ですか?
通話の結果を保存するカスタムクラスを作成します。その後、DownloadPageAsyncからTaskを返す –
Steve