Reputation: 53
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.
Upvotes: 2
Views: 16040
Reputation: 125197
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
When there is async method like GetResponseAsync
to do such job, its better to use it and avoid creating task.
Consider reading great posts of 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.
Upvotes: 1
Reputation: 12546
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
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
Upvotes: 14
Reputation: 303
You can use HttpClient in System.Net.Http for this(Assuming .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.
Upvotes: 0