C#,是否有“线程安全"之类的东西?溪流?
- 作者: 欣逗逼的快乐
- 来源: 51数据库
- 2023-02-13
问题描述
我正在将进程的输出重定向到我稍后阅读的流阅读器中.我的问题是我正在使用多个线程,这些线程应该有这个流的单独实例.当我去读入这个流时,线程混淆并开始奇怪地执行.
是否有制作线程安全流这样的东西?
我在流阅读器上的 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源









