2009-01-16 65 views
10

在ASP.Net應用程序中,我需要通過http POST將一些數據(urlEncodedUserInput)發送到外部服務器以響應用戶輸入,而不會阻止頁面響應。無論來自其他服務器的響應如何,我都不在乎有時請求失敗。這似乎運行良好(見下文),但我擔心它在後臺綁定資源,等待永遠不會使用的響應。如何在asp.net中發送http請求,無需等待響應,也不需要捆綁資源

下面的代碼:

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()進行清理還是可以防止請求被緩慢發送?

回答

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

我能想到的,你會得到來自其他要求快速響應的唯一方法是讓你發佈到網頁使用ThreadPool.QueueUserWorkItem打開一個線程,以便主線程在耗時的工作完成之前完成響應。你應該知道,一旦主線程退出,你將無法訪問HttpContext,這意味着沒有緩存,服務器變量等......共享驅動器將無法工作,除非你在新線程中模仿具有權限的用戶。線程很好,但有很多東西需要注意。

相關問題