patterncsharpModerate
Using statement in context of streams and WebClients
Viewed 0 times
statementandwebclientsstreamsusingcontext
Problem
Mostly a question on which approach would be better and when utilizing the
Link to my full answer using this sample: Stackoverflow Answer
Option 1:
Option 2:
using keyword, would it still be neccesary to close streams programatically. If an object implements IDisposable should using always be used?Link to my full answer using this sample: Stackoverflow Answer
Option 1:
WebClient webClient;
webClient = new WebClient();
string json = webClient.DownloadString(@"urlToTheJsonResponse");
MemoryStream stream = new MemoryStream((Encoding.UTF8.GetBytes(json)));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
stream.Position = 0;
GISData data = (GISData)ser.ReadObject(stream);
stream.Close();Option 2:
WebClient webClient;
MemoryStream stream;
string json;
GISData data;
using (webClient = new WebClient())
{
json = webClient.DownloadString(@"urlToTheJsonResponse");
}
using (stream = new MemoryStream((Encoding.UTF8.GetBytes(json))))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
data = (GISData)ser.ReadObject(stream);
stream.Close();
}
using (webClient = new WebClient())
{
webClient.DownloadFile(data.href, "C:/" + data.href.Substring(data.href.LastIndexOf("/") + 1));
}Solution
Under normal circumstances, you should always either call
But there are some types for which calling
If you are unsure whether you should dispose objects of some type or whether it's one of the few types where not disposing is safe, err on the side of caution and dispose it.
Dispose() explicitly or use a using block. This applies especially for streams and related types (like StreamWriter), where not disposing can have very visible bad consequences (e.g. the end of the text won't be written to the file).But there are some types for which calling
Dispose() doesn't actually do anything useful. And WebClient and MemoryStream are among them. They are IDisposable primarily because they inherit that interface from their base class (Component and Stream, respectively). So, I think your Option 1 is fine.If you are unsure whether you should dispose objects of some type or whether it's one of the few types where not disposing is safe, err on the side of caution and dispose it.
Context
StackExchange Code Review Q#9714, answer score: 14
Revisions (0)
No revisions yet.