C#, is there such a thing as a quot;thread-safequot; stream?(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?
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#,是否有“线程安全"之类的东西?溪流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#,是否有“线程安全"之类的东西?溪流?
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
