title: C# StreamReader: How to bound the maximum time of a sync ReadBlock call?
body: <p>I want to bound the maximum time it can take for reading a stream. The ReadTimeout property doesn't bound the maximum time, it only applies when no data is received in the ReadTimeout window. How can I make sure that the below code takes no more than N seconds to execute and if it takes more than N seconds, I want to cancel and free up all the underlying resources. </p>
  
  <pre><code>          using (WebResponse response = ExecuteHttpRequest(
                  httpRequestInputs.EndpointUrl,
                  new HttpMethod(httpRequestInputs.Method),
                  httpRequestInputs.Body,
                  httpRequestInputs.Headers))
              {
                  statusCode = ((HttpWebResponse)response).StatusCode;
  
                  using (var responseStream = response.GetResponseStream())
                  {
                      using (var streamReader = new StreamReader(responseStream))
                      {
                          var responseContent = new char[m_maxResponseSizeToBeRead];
                          var bytesRead = streamReader.ReadBlock(responseContent, 0, m_maxResponseSizeToBeRead);
                          if (!streamReader.EndOfStream){
                              isResponseSizeLimitExceeded = true;
                          }
                          else
                          {
                              result = new String(responseContent, 0, bytesRead);
                          }
                      }
                  }
              }
  </code></pre>
  
  <p>Can I wrap this in some task and then cancel that task after N seconds ? Will that free up the resources which are created in the task ?</p>