Is flushing automatic in TextWriter Synchronized?

680 Views Asked by At

I checked this code in debug. The file exists when it's executing, and string contents has some text.

        TextWriter.Synchronized(new StreamWriter(tmpOutput)).WriteLine(contents)

Yet the file is empty after this line is executing. Is Flush automatically run in Synchronized? WOuld there be anything else preventing WriteLine from working?

1

There are 1 best solutions below

3
Alexei Levenkov On BEST ANSWER

No, there is no automatic Flush call after every method.

TextWriter.Synchronized only guarantees thread safety - meaning it will prevent multiple threads from running calls to instance in parallel. There is no additional guarantees on top of that.

Note that it would significantly decrease performance of writer if it commits changes after each operation.

If you need to clarify how code is implemented - look at the source - https://referencesource.microsoft.com/#mscorlib/system/io/textwriter.cs,9e3dd0323cf4ee8b and observer that all methods are simple wrappers to call passed in writer with MethodImplOptions.Synchronized added to provide thread safety:

    [MethodImplAttribute(MethodImplOptions.Synchronized)]
    public override void Write(char value) {
            _out.Write(value);
    }