Problem with WebRequest and timeout

  • Thread starter news.microsoft.com
  • Start date
N

news.microsoft.com

Hello

I try to implement "retry" if connection to web ends with "time out". I want
to give a chance to prolong waiting for response. The following code is
taken from WebRequest.GetResponse() implementation. All I need to do is to
modify line with "to change". My client uses derrived HttpWebRequest. I
tried to implement new class MyHttpWebRequest and override GetResponse for
it, but how can I create instance of this class. In .Net there is used
special interface IWebRequestCreate and static method Create to creating
WebResponse object but I still don't know how to do this. Could somebody
help me? (maybee there is another solution?). Thanks a lot.

Shark

public override WebResponse GetResponse()
{
IAsyncResult result1;
Exception exception1;
if (this._HaveResponse)
{
this.CheckFinalStatus();
if (this._HttpResponse != null)
{
return this._HttpResponse;
}

}
result1 = base.BeginGetResponse(null, null);
if ((this._Timeout != -1) && !result1.IsCompleted)
{
try
{
result1.AsyncWaitHandle.WaitOne(this._Timeout, 0); //to change
if (!result1.IsCompleted)
{
base.Abort();
throw new WebException(SR.GetString("net_timeout"), 14);

}
}
catch (Exception exception2)
{
exception1 = exception2;
base.Abort();
throw;

}
 
J

Joerg Jooss

news.microsoft.com said:
Hello

I try to implement "retry" if connection to web ends with "time out".
I want to give a chance to prolong waiting for response. The
following code is taken from WebRequest.GetResponse() implementation.
All I need to do is to modify line with "to change".

Hm...

result1.AsyncWaitHandle.WaitOne(this._Timeout, 0); //to change

The second parameter is false, not 0. As you can see, it already uses a
timeout, so there's no reason to toy with HttpWebRequest's innards ;-)
Just use the HttpWebRequest.Timeout property.
My client uses
derrived HttpWebRequest. I tried to implement new class
MyHttpWebRequest and override GetResponse for it, but how can I
create instance of this class. In .Net there is used special
interface IWebRequestCreate and static method Create to creating
WebResponse object but I still don't know how to do this. Could
somebody help me? (maybee there is another solution?). Thanks a lot.

You can also use the asynchronous BeginGetResponse(), which returns an
IAsyncResult object to create an timeout that is independent of the Timeout
property mentioned above. This looks roughly like this:

HttpWebRequest request =
(HttpWebRequest) WebRequest.Create(http://host/path/to/resource.html);

IAsynchResult ar = request.BeginGetResponse(
new AsyncCallback(ResponseCallback),
request);

ThreadPool.RegisterWaitForSingleObject(
ar.AsyncWaitHandle,
new WaitOrTimerCallback(TimeoutCallback),
request,
5000, // 5 secs
true);

Cheers,
 
Top