title: C# StreamReader causing +200ms overhead to read data from source
body: <p>There is an issue where we are seeing some periodic +200ms overhead on reading the Input Stream from a Stream Reader when there is load on the system. I am wondering has anyone else seen this and if they have done anything to fix it? </p>
  
  <blockquote>
    <p>The following is the code: </p>
  </blockquote>
  
  <pre><code>string requestBody;
  var streamReaderTime = Stopwatch.StartNew();
  using (var streamReader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
  {
      var allLines = streamReader.ReadLines();
      var request = new StringBuilder();
      allLines.ForEach(line =&gt; request.Append(line));
      requestBody = request.ToString();
  }
  streamReaderTime.Stop();
  </code></pre>
  
  <blockquote>
    <p>ReadLine is just as follows: </p>
  </blockquote>
  
  <pre><code>public static IEnumerable&lt;string&gt; ReadLines(this StreamReader reader)
  {
     while (!reader.EndOfStream)
     { 
       yield return reader.ReadLine();
     }
  }
  </code></pre>
  
  <p>Note: Using ReadLines() or ReadToEnd() makes very little difference if any.</p>
  
  <p>We run performance tests overnight and we are seeing the following behavior just from graphing streamReaderTime.</p>
  
  <p><a href="https://i.stack.imgur.com/C2FrI.png" rel="nofollow"><img src="https://i.stack.imgur.com/C2FrI.png" alt="enter image description here"></a></p>
  
  <p>A single request takes between 45ms and 70ms to execute but it can be seen from the screenshot that it is adding on a fixed value and sometimes an even bigger spike. I saw it before being at around 1.5 seconds. </p>
  
  <p>If anyone has any solutions/suggestions it would be greatly appreciated. </p>
  
  <p>Edit : I did have ReadToEnd() instead of ReadLines() and that got rid of the StringBuilder but it was still the same overhead. Is there an alternative to StreamReader, just to test out even? It does seem like GC cost since having a request ever ten seconds does not effect it, but the exact same request per second will cause this overhead to happen. Also I am not able to reproduce it locally either, it is only in the virtual environment that this is happening.</p>