views:

102

answers:

2

Hi,

I kind of new to the hole threading stuff so bare with me here..

I have a aspx-page that takes some input and makes a reqest:

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 ALOT.

Is there any advantage to make every request in a separate thread and exactly how would that look like?

Thx!

A: 

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

ErikHeemskerk
Great! Thank you.
Mike Ribeiro
@Erik: I have to downvote since you didn't mention any of the issues specific to ASP.NET pages.
John Saunders
A: 

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:

John Saunders