So far, I have made synchronous HttpWebRequest calls in WinForms applications. I want to start doing this asynchronously so as not to block the UI thread and not freeze. So I'm trying to switch to HttpClient, but I'm also new to async and tasks and don't quite understand it.
I can run the request and get a response and isolate the data I want (result, reasonPhrase, headers, code), but I don’t know how to return them for display in textBox1. I also need to grab ex.message and return to the form if a timeout occurs or the connection fails.
Each individual example that I see has the values written in Console.WriteLine () where they are available, but I need them to return to the form for display and processing and have a hard time understanding how to do this.
Here is a simple example:
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();
textBox1.AppendText("done Test()\r\n");
}
static async void DownloadPageAsync()
{
using (HttpClient client = new HttpClient())
{
try
{
using (HttpResponseMessage response = await client.GetAsync(new Uri("http://192.168.2.70/")))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
string reasonPhrase = response.ReasonPhrase;
HttpResponseHeaders headers = response.Headers;
HttpStatusCode code = response.StatusCode;
}
}
}
catch (Exception ex)
{
}
}
}
}
}
Any helpful hints or tips?
source
share