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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.