HttpWebRequest ReadWriteTimeout is ignored in .NET; works at mono

When writing data to a web server, my tests show HttpWebRequest.ReadWriteTimeout is ignored, unlike

+3
source share
1 answer

It seems like an error when the recording timeout specified in the Stream instance returned to you by BeginGetRequestStream () does not extend to the native socket. I will log an error to make sure that this problem is fixed for a future version of the .NET Framework.

Here is a workaround.

private static void SetRequestStreamWriteTimeout(Stream requestStream, int timeout)
{
  // Work around a framework bug where the request stream write timeout doesn't make it
  // to the socket. The "m_Chunked" field indicates we are performing chunked reads. Since
  // this stream is being used for writes, the value of this field is irrelevant except
  // that setting it to true causes the Eof property on the ConnectStream object to evaluate
  // to false. The code responsible for setting the socket option short-circuits when it
  // sees Eof is true, and does not set the flag. If Eof is false, the write timeout
  // propagates to the native socket correctly.

  if (!s_requestStreamWriteTimeoutWorkaroundFailed)
  {
    try
    {
      Type connectStreamType = requestStream.GetType();
      FieldInfo fieldInfo = connectStreamType.GetField("m_Chunked", BindingFlags.NonPublic | BindingFlags.Instance);
      fieldInfo.SetValue(requestStream, true);
    }
    catch (Exception)
    {
      s_requestStreamWriteTimeoutWorkaroundFailed = true;
    }
  }

  requestStream.WriteTimeout = timeout;
}

private static bool s_requestStreamWriteTimeoutWorkaroundFailed;
+4
source

Source: https://habr.com/ru/post/1742027/


All Articles