3

Ok there are 2 ways of writing text to a file in multi threaded system

Which one is better than other

First case : having a static object to lock streamwriter and do operations

Second case having :

     TextWriter twWaitingToBeFetched;
     twWaitingToBeFetched = TextWriter.Synchronized(new StreamWriter(stringPath, true));
     twWaitingToBeFetched.WriteLine(srNewComposedUrl);
     twWaitingToBeFetched.Flush();

Now which one is better do you think and why ?

I need multiple threads tasks to write same stream

C# .net 4.5 - WPF application

Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • Do you need multiple threads to write to the file using the same stream? Or can multiple threads use their own stream to the same file to append content? – Frode Aug 13 '14 at 11:38
  • @Frode I need multiple threads to write same stream – Furkan Gözükara Aug 13 '14 at 11:41
  • Both are almost same except that lock field shouldn't be static(if `twWaitingToBeFetched` is instance field). static locks will synchronize two unrelated instances. – Sriram Sakthivel Aug 13 '14 at 11:48

1 Answers1

4

If you use the 2nd variant locking is implicit and hidden. Calling code does know anything about the locks. In fact it might wrongly assume that two calls to WriteLine are atomic and will appear one after the other in the output.

Use explicit locking so that you can better control what operations appear to be atomic.


 TextWriter twWaitingToBeFetched;
 twWaitingToBeFetched = TextWriter.Synchronized(new StreamWriter(stringPath, true));
 twWaitingToBeFetched.WriteLine(srNewComposedUrl);
 twWaitingToBeFetched.Flush();

This does not synchronize anything because each WriteLine is dispatched on a new, independent synchronized writer. You also need to properly dispose objects and not call Flush unnecessarily.

usr
  • 168,620
  • 35
  • 240
  • 369