简体   繁体   English

使用TextWriter.Synchronized或在多线程文件IO中锁定 - C#WPF .net 4.5

[英]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 第一种情况:拥有一个静态对象来锁定streamwriter并进行操作

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 C#.net 4.5 - WPF应用程序

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. 事实上,它可能错误地假设对WriteLine两次调用是原子的,并且将在输出中一个接一个地出现。

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. 这不会同步任何内容,因为每个WriteLine都是在一个新的独立同步WriteLine器上调度的。 You also need to properly dispose objects and not call Flush unnecessarily. 您还需要正确处理对象,而不是不必要地调用Flush

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM