到目前为止,我一直在WinForms应用程序中进行同步HttpWebRequest调用。我想开始异步执行此操作,以免阻塞UI线程并使它挂起。因此,我尝试切换到HttpClient,但是我对异步和任务还是陌生的,还不太了解。
Up until now, I've been making synchronous HttpWebRequest calls in WinForms applications. I want to start doing it asynchronously so as to not block the UI thread and have it hang. Therefore, I am attempting to switch to HttpClient, but I am also new to async and tasks and don't quite get it, yet.
我可以启动请求并得到响应并隔离我想要的数据(结果,reasonPhrase,标头,代码),但不知道如何取回该数据以显示在textBox1中。如果发生超时或无法连接消息,我还需要捕获ex.message并返回到表单。
I can launch the request and get a response and isolate the data I want (result, reasonPhrase, headers, code) but don't know how to get that back for display in textBox1. I also need to capture ex.message and return to the form if a timeout or cannot connect message occurs.
我看到的每个示例都将值写入Console.WriteLine ()暂时可以使用它们,但是我需要它们返回到表单进行显示和处理,并且很难理解如何使用。
Every single example I see has the values written to Console.WriteLine() at the point they are available, but I need them returned back to the form for display and processing and have a hard time understanding how.
这里有一个简单的示例:
Here's 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(); // 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("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. } } } } }有任何有用的提示或建议吗?
Any helpful hints or advice?
推荐答案创建一个模型以保存要返回的数据
create a model to hold the data you want to return
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 并在允许的事件处理程序中调用。
Avoid using async void methods. Convert the method to async Task and call it in the event handler where it is allowed.
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("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 应该
请参阅什么是引用在WebAPI客户端中每个调用创建新的HttpClient的开销?
更多推荐
如何将异步HttpClient响应返回给WinForm?
发布评论