Using thread in aspx-page making a webrequest
I开发者_StackOverflow社区 have an aspx-page that takes some input and makes a request:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}?{1}", strPostPath, strPostData));
request.Method = "GET";
request.Timeout = 5000; // set 5 sec. timeout
request.ProtocolVersion = HttpVersion.Version11;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
/do some with response
}
catch (WebException exce)
{
//Log some stuff
}
The thing is that this function is used a lot.
Is there any advantage to make every request in a separate thread and exactly how would that look like?
There are issues you must consider when using multiple threads in ASP.NET.
First of all, you have to realize that every ASP.NET page request arrives on a different worker thread. There are already a lot of threads in use!
Secondly, in your example, it seems that the page must wait for the response before returning HTML back to the browser. You won't save any time by using multiple threads, since the page still has to wait for the result.
The one benefit you might achieve comes from a combination of the above two issues. If your page is blocked waiting on the response from the web request, then that means you're holding up a worker thread while waiting for a response. That worker thread could instead be servicing another page request. This can impact scalability.
If scalability becomes a problem, you can use Asynchronous Pages to alleviate the problem in this case. With this model, when the page starts to wait on the web request, the page returns control back to ASP.NET. The worker thread may then service another request. When the response from the web request arrives, the page can continue processing. In the meantime, your precious worker threads don't spend their time doing nothing.
See:
- Wicked Code: Asynchronous Pages in ASP.NET 2.0
- Wicked Code: Scalable Apps and Asynchronous Programming in ASP.NET
The advantage of doing this on a separate thread would be that your thread wouldn't block while the request is being retrieved.
However, actually creating a thread and executing it is not recommended; you end up with a lot of synchronization problems--when is it done and how will you get the results etc. It is best to use an asynchronous method (which still uses another thread) as it allows you to simply specify a method to be called when the request has been retrieved.
For HttpWebRequest.GetResponse
, the async method is HttpWebRequest.BeginGetResponse
精彩评论