简体   繁体   中英

C# Using StreamReader, Disposing of Response Stream

Okay so let's say I have a program which makes a WebRequest and gets a WebResponse, and uses that WebResponse for a StreamReader in a using statement, which obviously gets disposed of after, but what about the WebResponse stream? For example:

WebResponse response = request.GetResponse();
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
   x = reader.ReadToEnd();
}

So obviously the StreamReader will get disposed after, and all resources devoted to it, but what about the Response Stream from response? Does that? Or should I do it like this:

WebResponse response = request.GetResponse();
using(Stream stream = response.GetResponseStream())
{
   using(StreamReader reader = new StreamReader(stream))
   {
      x = reader.ReadToEnd();
   }
}

Thanks

StreamReader assumes ownership of the Stream that you pass to its constructor. In other words, when you dispose the StreamReader object it will automatically also dispose the Stream object that you passed. That's very convenient and exactly what you want, simplifying the code to:

using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
   x = reader.ReadToEnd();
}

When I use Visual Studio 2013's Code Analysis, it claims the use of two 'usings' here will cause Dispose() to be called twice on 'response' and will generate a hidden 'System.ObjectDisposedException'?

warning CA2202: Microsoft.Usage : Object 'response' can be disposed more than once in method 'xxx'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

Has anyone else seen this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM