Chris Marisic
Chris Marisic

Reputation: 33098

Completely non-blocking HTTP request C# ASP.NET

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

Answers (3)

Michael Daw
Michael Daw

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

faby
faby

Reputation: 7558

You can use WebClient.UploadStringAsync Method for this purpose

This method does not block the calling thread.

It can throw

  1. ArgumentNullException
  2. WebException

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

theDarse
theDarse

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

Related Questions