0

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?

Jeanne Lane
  • 495
  • 1
  • 9
  • 26

1 Answers1

1

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);
    }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I had better luck with this: `using (TextWriter tw = new StreamWriter(tmpOutput)) { tw.WriteLine(contents); }` – Jeanne Lane Jan 25 '17 at 16:31
  • When you say "it would significantly decrease performance of writer if it commits changes after each operation" - are you talking about writers in general or specifically in the case of a synchronized writer? – pushkin Apr 01 '22 at 14:46
  • 1
    @pushkin all writes - as I said int he post synchronized wrapper does not change *behavior* of the writer. It is generally expected that all "writers" buffer their output as for most media writing is slow compared to memory access. Even at OS level "write through" behavior requires special flags. – Alexei Levenkov Apr 01 '22 at 17:17