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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25285096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:20:39  来源:igfitidea点击:

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

c#wpfmultithreadingstreamwritertextwriter

提问by MonsterMMORPG

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

C# .net 4.5 - WPF 应用程序

回答by usr

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 WriteLineare 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 WriteLineis dispatched on a new, independent synchronized writer. You also need to properly dispose objects and not call Flushunnecessarily.

这不会同步任何东西,因为每个WriteLine都是在一个新的、独立的同步写入器上分派的。您还需要正确处理对象,而不是Flush不必要地调用。