如何在asp.net中发送http请求而无需等待响应并且不占用资源

Stu*_*son 10 .net httpwebrequest

在ASP.Net应用程序中,我需要通过http POST将一些数据(urlEncodedUserInput)发送到外部服务器以响应用户输入,而不会阻止页面响应.来自其他服务器的响应无关紧要,我不关心请求有时是否失败.这似乎运行正常(见下文),但我担心它会在后台占用资源,等待永远不会被使用的响应.

这是代码:

httpRequest = WebRequest.Create(externalServerUrl);

httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

bytedata = Encoding.UTF8.GetBytes(urlEncodedUserInput);
httpRequest.ContentLength = bytedata.Length;

requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
Run Code Online (Sandbox Code Playgroud)

非常标准的东西,但通常在这一点上你可以调用httpRequest.getResponse()或httpRequest.beginGetResponse(),如果你想异步接收响应,但在我的场景中似乎没有必要.

我做对了吗?我应该调用httpRequest.Abort()来清理还是可以阻止请求在慢速连接上发送?

Ada*_*sek 7

我认为Threadpool.QueueUserWorkItem就是你要找的东西.通过添加lambda和匿名类型,这可以非常简单:

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);
Run Code Online (Sandbox Code Playgroud)