如何在asp.net中发送HTTP请求而无需等待响应且不占用资源 [英] How to send http request in asp.net without waiting for a response and without tying up resources

查看:276
本文介绍了如何在asp.net中发送HTTP请求而无需等待响应且不占用资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net应用程序中,我需要通过http POST将一些数据(urlEncodedUserInput)发送到外部服务器,以响应用户输入,而无需保持页面响应。不管其他服务器的响应是什么,我都不在乎请求有时是否失败。这似乎运行良好(请参阅下文),但我担心它在后台占用资源,等待永远不会使用的响应。

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. It doesn't matter what the response from the other server is, and I don't care if the request fails sometimes. This seems to be operating fine (see below) but I'm concerned that it's tying up resources in the background waiting for a response that will never be used.

这里是代码:

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

非常标准的东西,但是通常在这一点上,您将调用httpRequest.getResponse()或httpRequest.beginGetResponse ()如果您想异步接收响应,但是在我的情况下这似乎不是必需的。

Pretty standard stuff, but usually at this point you would call httpRequest.getResponse() or httpRequest.beginGetResponse() if you wanted to receive the response asynchronously, but this doesn't seem to be necessary in my scenario.

我在做正确的事情吗?我应该致电httpRequest.Abort()进行清理,还是可以阻止请求在慢速连接上发送?

Am I doing the right thing? Should I call httpRequest.Abort() to clean up or could this prevent the request from being sent on a slow connection?

推荐答案

我认为 Threadpool.QueueUserWorkItem 是您的目标重新寻找。通过添加lambda和匿名类型,这可以非常简单:

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

这篇关于如何在asp.net中发送HTTP请求而无需等待响应且不占用资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆