HttpWebRequest TimeOut Not working RRS feed

  • Question

  • User1857954827 posted

    public static string GetSupplierResponse_Async(string strxmlRQRS, string strHost, Int32 TimeOut)

    System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

    string strOutput = "";

    Task<string> result = GetSupplierResponsenew1(strxmlRQRS, strHost, TimeOut);
    string res = result.Result == null ? "" : result.Result;


    return res;

    catch (Exception ex)

    return strOutput;

    public static async Task<string> GetSupplierResponsenew1(string strxmlRQRS, string strHost, Int32 TimeOut)
    HttpWebRequest Request;
    Request = (HttpWebRequest)HttpWebRequest.Create(strHost);
    Request.Timeout = TimeOut;
    Request.ReadWriteTimeout = TimeOut;
    Request.Proxy = null;
    Request.Method = "POST";

    Request.Headers.Add("Accept-Encoding", "gzip");
    Request.ContentType = "text/xml;charset=utf-8";
    Request.Accept = "text/xml";
    Request.KeepAlive = false;

    ServicePointManager.DefaultConnectionLimit = 1000;
    using (Stream postStream = await Request.GetRequestStreamAsync())
    byte[] postBytes = Encoding.ASCII.GetBytes(strxmlRQRS);
    await postStream.WriteAsync(postBytes, 0, postBytes.Length);
    await postStream.FlushAsync();
    Task<string> Response;
    var response = (HttpWebResponse)await Request.GetResponseAsync();

    Stream streamResponse = response.GetResponseStream();
    if (response.ContentEncoding.ToLower().Contains("gzip"))
    streamResponse = new System.IO.Compression.GZipStream(streamResponse, System.IO.Compression.CompressionMode.Decompress);
    else if (response.ContentEncoding.ToLower().Contains("deflate"))
    streamResponse = new System.IO.Compression.DeflateStream(streamResponse, System.IO.Compression.CompressionMode.Decompress);

    StreamReader streamReader = new StreamReader(streamResponse);
    Response = streamReader.ReadToEndAsync();

    return await Response;

    catch (Exception ex)

    throw ex;

    Saturday, June 30, 2018 2:30 PM

All replies

  • User303363814 posted

    Please ask a question

    I read the first couple of lines and last couple of line of your code.  With no specific question or indication of what your expectations are or of what has happened then I choose not to read your code and give a line-by-line analysis.

    However, from reading the first and last few lines it is clear that you expect errors to occur, that you don't care and that you ignore them.  So, my first question would be "How do you know that there is no error in your code"?

    Sunday, July 1, 2018 11:27 PM
  • User1857954827 posted
    hi Paul,
    I have facing issue that let say I have give time out for 5 second but it does not work. my response may take longer then that. Yes there is no errors occur in my code I have check it giving successful out put. I am hiting this method parallel using task (150 request). so can you please let me know why time out not working
    Monday, July 2, 2018 5:02 AM
  • User303363814 posted

    Can you add a little detail to 'it does not work'?

    Does something happen that you do not expect to happen?

    Does something not happen that you expect to happen?

    Where in the code do you check to see if a timeout occurred? (It seems to me that you are ignoring all exceptions - bad programming technique)

    Instead of us having read through each line of your code and guess which line might have a problem and what it might be can you tell us which line of code does not do what you expect?  Tell us what you expect to happen and under what circumstances then tell us what actually happens.

    Monday, July 2, 2018 6:20 AM
  • User1857954827 posted

    Hi Paul,

    What is my issue that if i have given time out 5 second it should be time out with in five second . but it taking more time , i am saving each also how much time taken by each request.  can you please go through my code once. let me know if you need any thing from my end

    Monday, July 2, 2018 9:41 AM
  • User767034699 posted

    Hi there Chirag.jdk


    What is my issue that if i have given time out 5 second it should be time out with in five second . but it taking more time , i am saving each also how much time taken by each request.  can you please go through my code once. let me know if you need any thing from my end

    try the below code...

     private XmlDocument SendProcessingRequest(XmlDocument docData, string url)
                //Create an XML declaration. 
                XmlDeclaration xmldecl;
                xmldecl = docData.CreateXmlDeclaration("1.0", "UTF-8", null);
                //Add the new xml declaration node to the document.
                XmlElement root = docData.DocumentElement;
                docData.InsertBefore(xmldecl, root);
                // Data to send through. Must be byte array
                string postData = docData.InnerXml.ToString();
                byte[] data = Encoding.ASCII.GetBytes(postData);
                // Return type document
                XmlDocument xmlDocument = new XmlDocument();
                    // Create request
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ContentType = "application/xml";
                    request.Method = "POST";
                    request.Accept = "application/xml";
                      // Write the data to a buffer
                    byte[] buffer = data;
                    //string result = System.Convert.ToBase64String(buffer);
                    Stream reqstr = request.GetRequestStream();
                    reqstr.Write(buffer, 0, buffer.Length);
                    // Close
                    // Send and get response
                    // HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    WebResponse response = (WebResponse)request.GetResponse();
                    Stream s = response.GetResponseStream();
                    using (StreamReader sr = new StreamReader(s))
                        // Read intto string
                        string xmlResponse = sr.ReadToEnd();
                        // Load into xml
                catch (WebException ex)
                    _log.Debug(String.Format("Exception Payment Request Error: {0} Time 
                     {1}]", ex.Message.ToString(), DateTime.Now.ToString()));
                return xmlDocument;
    i have used log4net to log the error into a text file. you can use the db to store the error also
    see if that can help you.

    kind regards


    Monday, July 2, 2018 1:02 PM
  • User1857954827 posted

    Hi tony,

    this code dose not work for me. as your code is synchronous and i want asynchronous.

    Monday, July 2, 2018 1:04 PM
  • User303363814 posted

    The documentation seems very explicit to me

    Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream.

    You are not using either of those methods (as far as I can see)

    The BeginGetResponse method has a large clear note stating


    In the case of asynchronous requests, it is the responsibility of the client application to implement its own time-out mechanism. The following code example shows how to do it.

    Have you tried using the code example shown in the documentation? https://docs.microsoft.com/en-au/dotnet/api/system.net.httpwebrequest.begingetresponse?view=netframework-4.7.1

    Monday, July 2, 2018 1:08 PM
  • User1857954827 posted

    Hi Paul,

    Above link was not working it's giving me error 'The request was aborted: The connection was closed unexpectedly' when i use this code with my parallel task.

    My above code working fine with parallel task. but i have issue with TimeOut

    Wednesday, July 4, 2018 12:24 PM
  • User303363814 posted

    Can you explain your problem?  It would seem to be correct that when a request times out it is aborted.  So your statement seems to be telling me that everything is working properly.  Show your code, tell us what you expect to happen and what you observe happen and under what circumstances.

    Please note that saying 'not working' is very unhelpful.  Programming is about detail, detail and more detail..

    The documentation very explicitly states that the timeout property is for use with the GetResponse and GetRequestStream methods.  It has nothing to do with your code.  It doesn't matter how many times you repeat the question, it is never, ever going to work.  The documentation tells you that.

    Thursday, July 5, 2018 12:12 AM
  • User-233366979 posted

    I'm not sure if topic is still required to be answered. But just for people who will be looking for similar topic.

    var response = (HttpWebResponse)await Request.GetResponseAsync();

    TimeOut parameter applicable only for GetResponse() (synchronous one), not the GetResponseAsync(). In case of GetResponseAsync() TimeOut parameter will be totally ignored and getting request can stuck forever. For async method, unfortunately, custom timeout mechanics should be implemented. That's how I solved it in my case.

    int RequestTimeout = 30000;
    var responseTask = request.GetResponseAsync();
    WebResponse response = null;
    if (await Task.WhenAny(responseTask, Task.Delay(RequestTimeout)) == responseTask)
        response = await responseTask;
        if (response != null)
        throw new WebException("Async WebResponse timeout", WebExceptionStatus.Timeout);

    The key is in WhenAny() method. responseTask will be killled once Delay is finished. Maybe it doesn't look clean, but it works for me.

    Tuesday, February 9, 2021 10:20 AM