Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TextWriter.Synchronized or having lock in multithreaded file IO - C# WPF .net 4.5

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

like image 784
MonsterMMORPG Avatar asked Sep 13 '25 12:09

MonsterMMORPG


1 Answers

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.

like image 162
usr Avatar answered Sep 15 '25 02:09

usr