locked
How to set timeout of System.Net.HttpWebRequest? RRS feed

  • Question

  • Hi, I am developing metro style apps using vs2012 RTM (c# + xaml). Now I am using:

    System.Net.HttpWebRequest

    to request between client and server. I am wondering how to set timeout of it? 

    namespace System.Net
    {
        // Summary:
        //     Provides an HTTP-specific implementation of the System.Net.WebRequest class.
        public class HttpWebRequest : WebRequest
        {
            // Summary:
            //     Gets or sets the value of the Accept HTTP header.
            //
            // Returns:
            //     The value of the Accept HTTP header. The default value is null.
            public string Accept { get; set; }
            public virtual bool AllowReadStreamBuffering { get; set; }
            //
            // Summary:
            //     Gets or sets the value of the Content-type HTTP header.
            //
            // Returns:
            //     The value of the Content-type HTTP header. The default value is null.
            public override string ContentType { get; set; }
            public int ContinueTimeout { get; set; }
            //
            // Summary:
            //     Gets or sets the cookies associated with the request.
            //
            // Returns:
            //     A System.Net.CookieContainer that contains the cookies associated with this
            //     request.
            public virtual CookieContainer CookieContainer { get; set; }
            //
            // Summary:
            //     Gets or sets authentication information for the request.
            //
            // Returns:
            //     An System.Net.ICredentials that contains the authentication credentials associated
            //     with the request. The default is null.
            public override ICredentials Credentials { get; set; }
            //
            // Summary:
            //     Gets a value that indicates whether a response has been received from an
            //     Internet resource.
            //
            // Returns:
            //     true if a response has been received; otherwise, false.
            public virtual bool HaveResponse { get; }
            //
            // Summary:
            //     Specifies a collection of the name/value pairs that make up the HTTP headers.
            //
            // Returns:
            //     A System.Net.WebHeaderCollection that contains the name/value pairs that
            //     make up the headers for the HTTP request.
            //
            // Exceptions:
            //   System.InvalidOperationException:
            //     The request has been started by calling the System.Net.HttpWebRequest.GetRequestStream(),
            //     System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object),
            //     System.Net.HttpWebRequest.GetResponse(), or System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object)
            //     method.
            public override WebHeaderCollection Headers { get; set; }
            //
            // Summary:
            //     Gets or sets the method for the request.
            //
            // Returns:
            //     The request method to use to contact the Internet resource. The default value
            //     is GET.
            //
            // Exceptions:
            //   System.ArgumentException:
            //     No method is supplied.-or- The method string contains invalid characters.
            public override string Method { get; set; }
            //
            // Summary:
            //     Gets the original Uniform Resource Identifier (URI) of the request.
            //
            // Returns:
            //     A System.Uri that contains the URI of the Internet resource passed to the
            //     System.Net.WebRequest.Create(System.String) method.
            public override Uri RequestUri { get; }
            public virtual bool SupportsCookieContainer { get; }
            //
            // Summary:
            //     Gets or sets a System.Boolean value that controls whether default credentials
            //     are sent with requests.
            //
            // Returns:
            //     true if the default credentials are used; otherwise false. The default value
            //     is false.
            //
            // Exceptions:
            //   System.InvalidOperationException:
            //     You attempted to set this property after the request was sent.
            public override bool UseDefaultCredentials { get; set; }
    
            // Summary:
            //     Cancels a request to an Internet resource.
            public override void Abort();
            //
            // Summary:
            //     Begins an asynchronous request for a System.IO.Stream object to use to write
            //     data.
            //
            // Parameters:
            //   callback:
            //     The System.AsyncCallback delegate.
            //
            //   state:
            //     The state object for this request.
            //
            // Returns:
            //     An System.IAsyncResult that references the asynchronous request.
            //
            // Exceptions:
            //   System.Net.ProtocolViolationException:
            //     The System.Net.HttpWebRequest.Method property is GET or HEAD.-or- System.Net.HttpWebRequest.KeepAlive
            //     is true, System.Net.HttpWebRequest.AllowWriteStreamBuffering is false, System.Net.HttpWebRequest.ContentLength
            //     is -1, System.Net.HttpWebRequest.SendChunked is false, and System.Net.HttpWebRequest.Method
            //     is POST or PUT.
            //
            //   System.InvalidOperationException:
            //     The stream is being used by a previous call to System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object)-or-
            //     System.Net.HttpWebRequest.TransferEncoding is set to a value and System.Net.HttpWebRequest.SendChunked
            //     is false.-or- The thread pool is running out of threads.
            //
            //   System.NotSupportedException:
            //     The request cache validator indicated that the response for this request
            //     can be served from the cache; however, requests that write data must not
            //     use the cache. This exception can occur if you are using a custom cache validator
            //     that is incorrectly implemented.
            //
            //   System.Net.WebException:
            //     System.Net.HttpWebRequest.Abort() was previously called.
            //
            //   System.ObjectDisposedException:
            //     In a .NET Compact Framework application, a request stream with zero content
            //     length was not obtained and closed correctly. For more information about
            //     handling zero content length requests, see Network Programming in the .NET
            //     Compact Framework.
            public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state);
            //
            // Summary:
            //     Begins an asynchronous request to an Internet resource.
            //
            // Parameters:
            //   callback:
            //     The System.AsyncCallback delegate
            //
            //   state:
            //     The state object for this request.
            //
            // Returns:
            //     An System.IAsyncResult that references the asynchronous request for a response.
            //
            // Exceptions:
            //   System.InvalidOperationException:
            //     The stream is already in use by a previous call to System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object)-or-
            //     System.Net.HttpWebRequest.TransferEncoding is set to a value and System.Net.HttpWebRequest.SendChunked
            //     is false.-or- The thread pool is running out of threads.
            //
            //   System.Net.ProtocolViolationException:
            //     System.Net.HttpWebRequest.Method is GET or HEAD, and either System.Net.HttpWebRequest.ContentLength
            //     is greater than zero or System.Net.HttpWebRequest.SendChunked is true.-or-
            //     System.Net.HttpWebRequest.KeepAlive is true, System.Net.HttpWebRequest.AllowWriteStreamBuffering
            //     is false, and either System.Net.HttpWebRequest.ContentLength is -1, System.Net.HttpWebRequest.SendChunked
            //     is false and System.Net.HttpWebRequest.Method is POST or PUT.-or- The System.Net.HttpWebRequest
            //     has an entity body but the System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object)
            //     method is called without calling the System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object)
            //     method. -or- The System.Net.HttpWebRequest.ContentLength is greater than
            //     zero, but the application does not write all of the promised data.
            //
            //   System.Net.WebException:
            //     System.Net.HttpWebRequest.Abort() was previously called.
            public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
            //
            // Summary:
            //     Ends an asynchronous request for a System.IO.Stream object to use to write
            //     data.
            //
            // Parameters:
            //   asyncResult:
            //     The pending request for a stream.
            //
            // Returns:
            //     A System.IO.Stream to use to write request data.
            //
            // Exceptions:
            //   System.ArgumentNullException:
            //     asyncResult is null.
            //
            //   System.IO.IOException:
            //     The request did not complete, and no stream is available.
            //
            //   System.ArgumentException:
            //     asyncResult was not returned by the current instance from a call to System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object).
            //
            //   System.InvalidOperationException:
            //     This method was called previously using asyncResult.
            //
            //   System.Net.WebException:
            //     System.Net.HttpWebRequest.Abort() was previously called.-or- An error occurred
            //     while processing the request.
            public override Stream EndGetRequestStream(IAsyncResult asyncResult);
            //
            // Summary:
            //     Ends an asynchronous request to an Internet resource.
            //
            // Parameters:
            //   asyncResult:
            //     The pending request for a response.
            //
            // Returns:
            //     A System.Net.WebResponse that contains the response from the Internet resource.
            //
            // Exceptions:
            //   System.ArgumentNullException:
            //     asyncResult is null.
            //
            //   System.InvalidOperationException:
            //     This method was called previously using asyncResult.-or- The System.Net.HttpWebRequest.ContentLength
            //     property is greater than 0 but the data has not been written to the request
            //     stream.
            //
            //   System.Net.WebException:
            //     System.Net.HttpWebRequest.Abort() was previously called.-or- An error occurred
            //     while processing the request.
            //
            //   System.ArgumentException:
            //     asyncResult was not returned by the current instance from a call to System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object).
            public override WebResponse EndGetResponse(IAsyncResult asyncResult);
        }
    }

    No Timeout property found. Could anyone help?

    Thanks in advance.


    dollar zhang

    Wednesday, September 19, 2012 11:12 AM

Answers

  • you can do that using tasks...

    await Task.WhenAny(request.GetResponseAsync(), Task.Delay(45000));
    

    it will continue when any of the 2 tasks is completed: the request or the delay (timeout)

    • Proposed as answer by Pedro Alonso Wednesday, September 19, 2012 2:26 PM
    • Marked as answer by Dollar Zhang Thursday, September 20, 2012 6:31 AM
    Wednesday, September 19, 2012 2:26 PM

All replies

  • hey there,

    Timeout property is inherited from the WebRequest class... from the example on msdn page for httpwebrequest:

    // Create a new 'HttpWebRequest' Object to the mentioned URL.
    HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
    
    // Set the  'Timeout' property of the HttpWebRequest to 10 milliseconds.
    myHttpWebRequest.Timeout=10;
    
    // A HttpWebResponse object is created and is GetResponse Property of the HttpWebRequest associated with it 
    HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();


    Can Bilgin
    Blog CompuSight

    Wednesday, September 19, 2012 11:25 AM
  • Thanks for your prompt response. I also had read this document but when I try to set Timeout property, it just can't find this property. And I find another thread about this question which indicated that "no Timeout property in HttpWebRequest".

    http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/8bea8964-b7bb-4ef4-a5f7-c2357933758d

    Is that true? Thanks again.


    dollar zhang

    Wednesday, September 19, 2012 11:52 AM
  • if you are using a portable library this property might not be supported... But if it is supposed to be supported by WinRT.


    Can Bilgin
    Blog CompuSight

    Wednesday, September 19, 2012 12:04 PM
  • you can do that using tasks...

    await Task.WhenAny(request.GetResponseAsync(), Task.Delay(45000));
    

    it will continue when any of the 2 tasks is completed: the request or the delay (timeout)

    • Proposed as answer by Pedro Alonso Wednesday, September 19, 2012 2:26 PM
    • Marked as answer by Dollar Zhang Thursday, September 20, 2012 6:31 AM
    Wednesday, September 19, 2012 2:26 PM
  • It works!! Thanks, Pedro.

    dollar zhang

    Thursday, September 20, 2012 5:33 AM