我正在将进程的输出重定向到我稍后阅读的流阅读器中.我的问题是我正在使用多个线程,这些线程应该有这个流的单独实例.当我去读入这个流时,线程混淆并开始奇怪地执行.
是否有制作线程安全流这样的东西?
我在流阅读器上的 ReadToEnd 上加锁,以及我所做的那一行: reader = 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;
框架中内置了 SynchronizedStream,它们只是不公开类供您查看/子类等,但您可以将任何流转换为同步流使用
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#,是否有“线程安全"之类的东西?溪流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!