英文:
Do I need to dispose of StreamWriter when generating a stream from a string?
问题
以下是翻译好的代码:
// 原始代码
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
// 更新后的代码
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
using(var writer = new StreamWriter(stream, leaveOpen: true))
{
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}
英文:
So I have the following code to convert a string to a MemoryStream
https://stackoverflow.com/a/1879470/2987066
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Would it be correct to dispose of the StreamWriter
as it implements IDisposable
but as we need to return the stream we use the leaveOpen
property on the StreamWriter
so would the following be correct to deal with memory leaks or is it not necessary?
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
using(var writer = new StreamWriter(stream, leaveOpen: true))
{
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}
答案1
得分: 0
从评论中看,StreamWriter
实际上不会持有任何需要释放的资源,因此在以下情况下不需要在 using
语句中包装它。
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
另外,即使在 StreamWriter
包装在 using
语句中,MemoryStream
仍然需要释放。
StreamWriter
上的 Dispose
方法只会在底层流上调用 Close
,因此必须显式调用 Dispose
方法来释放 MemoryStream
。
英文:
From the comments. StreamWriter
doesnt actually hold any resources itself that need to be disposed of and therefore doesnt need to be wrapped in a using statement in the following scenario.
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
As an aside MemoryStream
does need disposing of, even if the StreamWriter
is wrapped in a using statement.
The Dispose
method on StreamWriter
just calls Close
on the underlying stream not Dispose
hence why Dispose
must be explicitly called on the MemoryStream
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论