How to send http request in asp.net without waiting for a response and without tying up resources

后端 未结 2 636
无人共我
无人共我 2020-12-29 12:36

In an ASP.Net application, I need to send some data (urlEncodedUserInput) via http POST to an external server in response to user input, without holding up the page response

2条回答
  •  臣服心动
    2020-12-29 12:58

    I think Threadpool.QueueUserWorkItem is what you're looking for. With the addition of lambdas and anonymous types, this can be really simple:

    var request = new { url = externalServerUrl, input = urlEncodedUserInput };
    ThreadPool.QueueUserWorkItem(
        (data) =>
        {
             httpRequest = WebRequest.Create(data.url);
    
             httpRequest.Method = "POST";
             httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
    
             bytedata = Encoding.UTF8.GetBytes(data.input);
             httpRequest.ContentLength = bytedata.Length;
    
             requestStream = httpRequest.GetRequestStream();
             requestStream.Write(bytedata, 0, bytedata.Length);
             requestStream.Close();
             //and so on
         }, request);
    

提交回复
热议问题