runtime icon indicating copy to clipboard operation
runtime copied to clipboard

[Breaking Change] StreamWriter keeps working after being disposed if `leaveOpen: true` is used

Open jozkee opened this issue 3 years ago • 14 comments

In below snippet I was expecting an exception to be thrown but instead the StreamWriter keeps working:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);

sw.Write("Hello");
sw.Dispose();

sw.Write(" World");
sw.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); // prints "Hello World".

If I change leaveOpen to false, it does throw as I expected.

Originally posted by @Jozkee in https://github.com/dotnet/runtime/pull/89477#discussion_r1277944108

cc @Neme12 @dersia


[Breaking Change] StreamWriter keeps working after being disposed if leaveOpen: true is used

We are fixing StreamWriter so that it correctly throws ObjectDisposedException after Dispose() / DisposeAsync() when constructed with leaveOpen: true. The fix is currently in PR #125189.

Related:

Goal

The goal is to align StreamWriter disposal behavior with StreamReader and standard IDisposable semantics. When leaveOpen: true, Dispose() should mark the writer as disposed (so subsequent operations throw) while leaving the underlying stream open. Currently, the _disposed flag is never set when leaveOpen: true, which means write and flush calls silently succeed after disposal.

Existing Behavior

When a StreamWriter is constructed with leaveOpen: true and then disposed, subsequent Write, Flush, and async variants continue to work without throwing any exception:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);
sw.Write("Hello");
sw.Dispose();
sw.Write(" World"); // No exception — writes succeed
sw.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
// prints "Hello World"

Note: StreamReader with the same leaveOpen: true flag correctly throws ObjectDisposedException after disposal. This inconsistency has existed since the leaveOpen parameter was introduced.

Breaking Change

After this fix, all write and flush operations on a disposed StreamWriter throw ObjectDisposedException, regardless of the leaveOpen parameter:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);
sw.Write("Hello");
sw.Dispose();
sw.Write(" World"); // Now throws ObjectDisposedException

The change is technically breaking because code that relied on the ability to write after disposal with leaveOpen: true will now throw at runtime. However, use-after-dispose is always documented as erroneous behavior in .NET, so we expect the practical impact to be low.

Error: System.ObjectDisposedException: Cannot write to a closed TextWriter.

Workaround: Remove usage patterns that write to a StreamWriter after calling Dispose() or DisposeAsync(). If you need to continue writing to the underlying stream, create a new StreamWriter wrapping it.

Affected APIs: All overloads of StreamWriter.Write, StreamWriter.WriteLine, StreamWriter.WriteAsync, StreamWriter.WriteLineAsync, StreamWriter.Flush, and StreamWriter.FlushAsync.

Feedback

We would love your feedback on this change. If you have scenarios where you depend on the current (pre-fix) behavior, please comment on this issue.

jozkee avatar Jul 28 '23 18:07 jozkee

Tagging subscribers to this area: @dotnet/area-system-io See info in area-owners.md if you want to be subscribed.

Issue Details

In below snippet I was expecting an exception to be thrown but instead the StreamWriter keeps working:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);

sw.Write("Hello");
sw.Dispose();

sw.Write(" World");
sw.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); // prints "Hello World".

If I change leaveOpen to false, it does throw as I expected.

Originally posted by @Jozkee in https://github.com/dotnet/runtime/pull/89477#discussion_r1277944108

Author: Jozkee
Assignees: -
Labels:

area-System.IO

Milestone: -

ghost avatar Jul 28 '23 18:07 ghost

Yeah, this is why I did the change in the first place and then I found out, that there are test on Stream that fail, I think it was the test NullWriterWriteText, but it will be another 2 hours until I have access to my pc again, then I can tell for certain.

To me it does not make sense for an disposed Writer to be write able or readable from. this does not mean, that the underlying stream is disposed if it isn't closeable. For StreamWriter it is implemented in a way that keeps the Writer in an undisposed state, if the underlying stream is not closeable. and as mentioned before I wanted to fix it, but there are tests that test that and when I blamed that file I could see, that those test are some of the oldest (I think it was over 8 years ago) added when the test file was created in the first place, so I can imaging that they were copied when net core was branched or the feature was ported.


From: David Cantú @.> Sent: Friday, July 28, 2023 8:29:12 PM To: dotnet/runtime @.> Cc: dersia @.>; Mention @.> Subject: [dotnet/runtime] StreamWriter keeps working after being disposed if leaveOpen: true is used (Issue #89646)

In below snippet I was expecting an exception to be thrown but instead the StreamWriter keeps working:

var ms = new MemoryStream(); var sw = new StreamWriter(ms, leaveOpen: true);

sw.Write("Hello"); sw.Dispose();

sw.Write(" World"); sw.Flush(); Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); // prints "Hello World".

If I change leaveOpen to false, it does throw as I expected.

Originally posted by @Jozkeehttps://github.com/Jozkee in #89477 (comment)https://github.com/dotnet/runtime/pull/89477#discussion_r1277944108

cc @Neme12https://github.com/Neme12 @dersiahttps://github.com/dersia

— Reply to this email directly, view it on GitHubhttps://github.com/dotnet/runtime/issues/89646, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AALXPJUHUEDA5AQ6JPQ343DXSQAHRANCNFSM6AAAAAA232XMGQ. You are receiving this because you were mentioned.Message ID: @.***>

dersia avatar Jul 28 '23 18:07 dersia

Note: This works as expected on StreamReader, i.e. it throws after being disposed, regardless of the value of leaveOpen.

Neme12 avatar Jul 28 '23 19:07 Neme12

I don't think so. have you tried? or did you mean anything other than StreamWriter?


From: Ashley @.> Sent: Friday, July 28, 2023 9:39:20 PM To: dotnet/runtime @.> Cc: dersia @.>; Mention @.> Subject: Re: [dotnet/runtime] StreamWriter keeps working after being disposed if leaveOpen: true is used (Issue #89646)

Note: This works as expected on StreamWriter, i.e. it throws after being disposed, regardless of leaveOpen.

— Reply to this email directly, view it on GitHubhttps://github.com/dotnet/runtime/issues/89646#issuecomment-1656228768, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AALXPJXYVU5ZUXSBEFOIDO3XSQIORANCNFSM6AAAAAA232XMGQ. You are receiving this because you were mentioned.Message ID: @.***>

dersia avatar Jul 28 '23 19:07 dersia

@dersia I meant StreamReader. I fixed the comment.

Neme12 avatar Jul 28 '23 19:07 Neme12

Added needs-breaking-change-doc-created label because this issue has the breaking-change label.

  1. [ ] Create and link to this issue a matching issue in the dotnet/docs repo using the breaking change documentation template, then remove this needs-breaking-change-doc-created label.

Tagging @dotnet/compat for awareness of the breaking change.

ghost avatar Jul 28 '23 20:07 ghost

If we fix this someone somewhere will likely get broken, so we either don't fix it or we do and document it as a breaking change.

jozkee avatar Jul 28 '23 20:07 jozkee

So you think we should make the breaking change as part of this ticket and net8? I would suggest do get this in and then create a new bug ticket and fix and break it for net9, this would give us time to see if there are many broken during net9 preview times. not sure if so close to rc, this is a good thing to do. I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush).

I can also take care of that other ticket, since if have all the code for it and the PR for that other ticket could target milestone 9.


From: David Cantú @.> Sent: Friday, July 28, 2023 10:07:48 PM To: dotnet/runtime @.> Cc: dersia @.>; Mention @.> Subject: Re: [dotnet/runtime] StreamWriter keeps working after being disposed if leaveOpen: true is used (Issue #89646)

If we fix this someone somewhere will likely get broken, so we either don't fix it or we do and document it as a breaking change.

— Reply to this email directly, view it on GitHubhttps://github.com/dotnet/runtime/issues/89646#issuecomment-1656263868, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AALXPJXTBU6URTLNC26BWT3XSQLZJANCNFSM6AAAAAA232XMGQ. You are receiving this because you were mentioned.Message ID: @.***>

dersia avatar Jul 28 '23 20:07 dersia

I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush)

StreamReader does throw when disposed: image

Neme12 avatar Jul 28 '23 20:07 Neme12

hmmm interesting, I was pretty sure I wrote a test for this. maybe it was just for DisposeAsync. i will look at it, once I get home.


From: Ashley @.> Sent: Friday, July 28, 2023 10:26:59 PM To: dotnet/runtime @.> Cc: dersia @.>; Mention @.> Subject: Re: [dotnet/runtime] StreamWriter keeps working after being disposed if leaveOpen: true is used (Issue #89646)

I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush)

StreamReader does throw when disposed: [image]https://user-images.githubusercontent.com/11444821/256926081-7c9d73f8-10bd-461f-b2af-a4fda2a1f877.png

— Reply to this email directly, view it on GitHubhttps://github.com/dotnet/runtime/issues/89646#issuecomment-1656292470, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AALXPJR4ZOUZXLXEPKIJ4XTXSQOBHANCNFSM6AAAAAA232XMGQ. You are receiving this because you were mentioned.Message ID: @.***>

dersia avatar Jul 28 '23 20:07 dersia

I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush)

StreamReader does throw when disposed: image

So I looked into the code and found out, why the Reader tests aren't throwing, although your testing throws. And I am not sure, if what I found is a as bad sign as I think it is. So basically the test are not really testing StreamReader, they are testing an internal derived class called NullStreamReader https://github.com/dotnet/runtime/blob/4ed355098d50ea419931025ed466d0265c55b22f/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs#L1412 which overrides Dispose:

protected override void Dispose(bool disposing)
{
    // Do nothing - this is essentially unclosable.
}

So the Tests on Stream.NullTest.cs won't test any of the Dispose logic of StreamReader. So there are now 2 different things I am wondering about.

  1. Should we remove the Dispose override on this class?
  2. do we need to override DisposeAync() on this class, now that DisposeAsync was newly added to StreamReader?

Not sure which is the right option here. I think to be fully correct, one of the two need to happen as part of https://github.com/dotnet/runtime/pull/89477 and right now I am leaning more towards the latter. Although, this makes all test that involve Reading after dispose useless.

dersia avatar Jul 29 '23 10:07 dersia

So you think we should make the breaking change as part of this ticket and net8? I would suggest do get this in and then create a new bug ticket and fix and break it for net9, this would give us time to see if there are many broken during net9 preview times. not sure if so close to rc, this is a good thing to do. I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush). I can also take care of that other ticket, since if have all the code for it and the PR for that other ticket could target milestone 9.

As I was looking at this from my phone, I didn't realize that this is a separate issue, so don't mind this

dersia avatar Jul 29 '23 10:07 dersia

Summary

When StreamWriter is constructed with leaveOpen: true, calling Dispose() does not mark the writer as disposed. Subsequent Write and Flush calls succeed instead of throwing ObjectDisposedException. This is inconsistent with StreamReader, which correctly throws after disposal regardless of leaveOpen. Filed by @jozkee (MS employee) and confirmed as a genuine inconsistency.

Expected Fix

In StreamWriter.Dispose(bool), when leaveOpen is true, the method currently skips closing the underlying stream but also skips setting any "disposed" flag. The fix should set the internal _disposed flag (or null out the internal _stream field like the leaveOpen: false path does) so that subsequent operations throw ObjectDisposedException. Note: this is technically a breaking change since someone could be relying on the current behavior, but the team acknowledged it as a bug worth fixing.

Test Coverage

  • Add a test: create StreamWriter with leaveOpen: true, dispose it, then call Write — should throw ObjectDisposedException.
  • Add a test: same scenario with DisposeAsync — should also throw on subsequent writes.
  • Add a test confirming StreamReader with leaveOpen: true already throws after dispose (parity check).
  • Ensure existing StreamWriter tests still pass.

Repro

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);

sw.Write("Hello");
sw.Dispose();

sw.Write(" World"); // Should throw ObjectDisposedException, but doesn't
sw.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
// Actual:   prints "Hello World"
// Expected: ObjectDisposedException on sw.Write(" World")

jeffhandley avatar Feb 08 '26 10:02 jeffhandley

The consensus in #125189 is that the risk of breaking existing code outweighs the benefit given no active customer demand. Preserving the current behavior for backward compatibility.

ViveliDuCh avatar Mar 17 '26 05:03 ViveliDuCh