如何使用 NamedPipeServerStream 和 StreamReader 类传递类和结构
我试图弄清楚如何在线程之间使用命名管道传递类/结构/等..(我试图使用秒表测量一些性能并将其与其他方法进行比较..)
无论如何,我已经阅读过的所有文档find正在谈论使用StreamReader和readline从NamedPipeServerStream获取数据。然而 readline 是一个字符串,如果我传递的不是字符串,我如何实际使用命名管道中的数据。
谢谢, 埃亚勒
I am trying to figure out how to pass a class/struct/etc.. using named pipe between thread(I am trying to measure some performance using the stopwatch and compare it to other methods..)
Anyway , All the documention I've found is talking about using StreamReader and readline to get the data from the NamedPipeServerStream. However readline is a string, how do I actually use the data from the named pipe if I am passing something that is not a string.
Thanks,
Eyal
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NamedPipeServerStream
是一个流 - 因此它适合开箱即用的二进制数据。只需将其视为普通流,而不是将其包装在StreamReader
中。至于传递对象 - 如果您严格位于单个进程中,为什么要使用命名管道?只需创建一个内存中的生产者/消费者队列。
NamedPipeServerStream
is a stream - so it's fine for binary data out of the box. Just treat it like a normal stream, rather than wrapping it in aStreamReader
.As for passing objects - why used named pipes if you're strictly within a single process? Just create an in-memory producer/consumer queue.
使用 BinaryFormatter 是在管道流中序列化对象的最简单方法。您需要使用 [Serialized] 属性来修饰类或结构。
然而,使用管道在线程之间“传递”数据是一种非常低效的方式。进程中的每个线程都可以访问相同的垃圾收集堆,只要线程在同一个 AppDomain 中运行,就不需要序列化。您确实需要同步对对象的访问,请使用 lock 语句。 ConcurrentQueue 类使其变得非常简单。
Using BinaryFormatter is the easiest way to serialize an object in and out of a pipe stream. You'll need to decorate the class or struct with the [Serializable] attribute.
Using a pipe is however a very inefficient way to "pass" data between threads. Every thread in a process has access to the same garbage collected heap, no serialization is required as long as the threads run in the same AppDomain. You do need to synchronize access to the object(s), use the lock statement. The ConcurrentQueue class makes it very simple.