C# 有没有“线程安全”之类的东西?溪流?
我将进程的输出重定向到稍后阅读的流读取器中。我的问题是我正在使用多个线程,它们应该有该流的单独实例。当我去读这个流时,线程捏造并开始奇怪地执行。
是否有创建线程安全流之类的东西?
编辑:我在流读取器的 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?
EDIT: I put locks on the ReadToEnd on the streamreader, and the line where I did: reader = proc.StandardOutput;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
框架内置了一个 SynchronizedStream,它们只是不公开类供您查看/子类等,但您可以使用将任何流转换为 SynchronizedStream
您应该将syncStream对象传递给需要它的每个线程,并且确保您永远不会尝试在代码中的其他位置访问 inStream。
SynchronizedStream 只是对所有读/写操作实现一个监视器,以确保线程对流具有互斥访问。
编辑:
看来他们也在框架中实现了 SynchronizedReader/SynchronizedWriter。
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
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.
The SynchronizedStream just implements a monitor on all read/write operation to ensure that a thread has mutually exclusive access to the stream.
Edit:
Appears they also implements a SynchronizedReader/SynchronizedWriter in the framework too.