在 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();
非常标准的东西,但通常在这一点上,如果您想异步接收响应,您会调用 httpRequest.getResponse() 或 httpRequest.beginGetResponse() ,但这在我的场景中似乎没有必要。
我做的事正确吗?我应该调用 http Request.Abort() 进行清理,还是可以阻止在慢速连接上发送请求?
I think 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)