完全无阻塞的HTTP请求C#ASP.NET

时间:2014-08-20 15:21:08

标签: c# asynchronous httprequest nonblocking asp.net-4.5

在我的应用程序Application_Start()事件期间,我想触发对地址的HTTP请求。我绝对不希望Application_Start()和App Start的任何费用以任何方式延迟。我不关心请求的回复。

以完全无阻塞的方式触发此请求的最正确方法是什么?

3 个答案:

答案 0 :(得分:4)

我会做这样的事情:

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();
        }
});

答案 1 :(得分:2)

我建议只是异步触发请求

using(var client = new HttpClient())
{
    client.PostAsJsonAsync("{url}",content)
}
例如,

将触发请求并继续

答案 2 :(得分:2)

您可以为此目的使用WebClient.UploadStringAsync方法

此方法不会阻止调用线程。

它可以抛出

  1. ArgumentNullException
  2. WebException
  3. 以这种方式使用

        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);