10

在 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() ,但这在我的场景中似乎没有必要。

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

4

2 回答 2

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);
于 2009-01-16T04:37:33.223 回答
0

我能想到的唯一方法是让您发布的页面使用 ThreadPool.QueueUserWorkItem 打开一个线程,以便主线程在耗时的工作之前完成响应完全的。您应该知道,一旦主线程退出,您将无法访问 HttpContext,这意味着没有缓存、服务器变量等......共享驱动器也将无法工作,除非您在新线程中模拟具有权限的用户。线程很好,但有很多事情需要注意。

于 2009-05-09T15:51:05.123 回答