[英]C# How to make this HttpRequest Async?
I have this code: 我有以下代码:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
using (WebResponse myResponse = myRequest.GetResponse())
{
using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
I want on the finish this request, run this code: 我想要完成此请求,运行以下代码:
MessageBox.Show("Finish");
Also, when i run this code, my program become freeze. 另外,当我运行此代码时,我的程序将冻结。 I think this problem solve with async HttpWebRequest. 我认为这个问题可以通过异步HttpWebRequest解决。
You can do it like (in an async method): 您可以这样做(在异步方法中):
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
using (WebResponse myResponse = await myRequest.GetResponseAsync())
{
using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
MessageBox.Show("Finish");
But I would recommend to use HttpClient 但是我建议使用HttpClient
using (var client = new HttpClient())
{
var result = await client.GetStringAsync(URL);
}
MessageBox.Show("Finish");
BTW: By using GetStringAsync
you use the encoding your site is using which may not be UTF8
顺便说一句:通过使用GetStringAsync
您使用您的网站使用的编码,它可能不是UTF8
EDIT 编辑
In order to " There are many different ways " that stated in original answer, its better to consider using async/await pattern that is done by Eser in his answer which is better answer 为了在原始答案中陈述“ 有许多不同的方式 ”,最好考虑使用由Eser在他的答案中完成的异步/等待模式, 这是更好的答案
When there is async method like GetResponseAsync
to do such job, its better to use it and avoid creating task. 当有诸如GetResponseAsync
类的异步方法来执行此类工作时,最好使用它并避免创建任务。
Consider reading great posts of Stephen Cleary: 考虑阅读Stephen Cleary的重要文章:
ORIGINAL 原版的
There are many different ways, for example: 有很多不同的方法,例如:
string url= "http://www.google.com";
string result = "";
Task.Run(() =>
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
using (WebResponse myResponse = myRequest.GetResponse())
{
using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
}).ContinueWith(x =>
{
//MessageBox.Show(result);
MessageBox.Show("Finished");
//here you can not easily set properties of form
//you should use Invoke pattern
});
This way the application will be completely responsive while the task is executing and there is no freezing anymore. 这样,应用程序将在任务执行时完全响应,并且不再冻结。
You can use HttpClient in System.Net.Http for this(Assuming .net > 4.5): 您可以为此在System.Net.Http中使用HttpClient(假设.net> 4.5):
HttpClient client = new HttpClient();
var code = client.GetAsync(URL).ContinueWith(x =>
{
MessageBox.Show("finish");
client.Dispose();
});
You should add some error checking in continue with to be sure. 为了确保继续,您应该添加一些错误检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.