需要释放 StreamWriter 吗在从字符串生成流时?

huangapple go评论59阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月14日 22:38:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75449387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定