C#中,有没有这样的事情作为"线程安全"流? [英] C#, is there such a thing as a "thread-safe" stream?
问题描述
我重定向过程的输出到这是我后来读一个StreamReader。我的问题是我使用的应该有这样流单独实例多个线程。当我去阅读,穿线呓语道此流并开始执行奇怪。
是否有这样的事情是把一个线程安全的流
的编辑:我把门锁上ReadToEnd的上的StreamReader,并在那里我做了线:读卡器= proc.StandardOutput;
I am redirecting the output of a process into a streamreader which I read later. My problem is I am using multiple threads which SHOULD have separate instances of this stream. When I go to read this stream in, the threading fudges and starts executing oddly.
Is there such a thing as making a thread-safe stream?
I put locks on the ReadToEnd on the streamreader, and the line where I did: reader = proc.StandardOutput;
推荐答案
类你有内置的框架SyncrhonizedStream,他们只是不暴露看一下/子等,但可以使用
There's a SyncrhonizedStream built into the framework, they just don't expose the class for you to look at/subclass etc, but you can turn any stream into a SynchronizedStream using
var syncStream = Stream.Synchronized(inStream);
您应该围绕传递syncStream对象需要它的每个线程,并确保你从来没有尝试访问inStream中的代码的其他地方。
You should pass the syncStream object around to each thread that needs it, and make sure you never try to access inStream elsewhere in code.
SynchronizedStream只是所有的读/写操作实现了监控,以确保一个线程到流互斥访问。
The SynchronizedStream just implements a monitor on all read/write operation to ensure that a thread has mutually exclusive access to the stream.
编辑:
看来他们也实现了框架太一SynchronizedReader / SynchronizedWriter
Appears they also implements a SynchronizedReader/SynchronizedWriter in the framework too.
var reader = TextReader.Synchronized(process.StandardOutput);
这篇关于C#中,有没有这样的事情作为"线程安全"流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!