Reputation: 33098
During my application's Application_Start()
event I want to fire off a HTTP request to an address. I absolutely do not want any cost incurred by Application_Start()
and for App Start to be delayed in any fashion. I do not care about the response from the request.
What is the most correct method for firing this request in a completely non-blocking fashion?
Upvotes: 2
Views: 4974
Reputation: 250
I would do something like this:
Task.Run(() =>
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://something.com/");
var content = new StringContent("content");
var result = httpClient.PostAsync("path/to/Service" , content);
result.Wait();
}
});
Upvotes: 4
Reputation: 7558
You can use WebClient.UploadStringAsync Method for this purpose
This method does not block the calling thread.
It can throw
use it in this way
var client = new WebClient();
//remove comment from next line to execute some code after UploadString complete
//client.UploadStringCompleted += new UploadStringCompletedEventHandler(function name to execute when finish);
var data = "data to send";
client.Headers.Add("Content-Type", "content type here");
client.UploadStringAsync(new Uri("http://www.yourDomain.com"), data);
Upvotes: 2
Reputation: 737
I would recommend just firing the request asynchronously
using(var client = new HttpClient())
{
client.PostAsJsonAsync("{url}",content)
}
for example will fire the request and continue
Upvotes: 2