在 C# 中实现管道 - 使用哪些(流?)类?
我很难理解如何在 C# 中使用流。
我计划有一个这种形式的类:
class Pipe {
public void PutChar(char c) { ... }
public char GetChar() { ... }
}
其想法是,一个线程将通过其 PutChar()
方法将字符放入此 Pipe
中,然后在其他线程上将使用 GetChar()
获取 Pipe
中的字符。
在 Java 中,我会使用 PipedReader 和 PipedWriter 类。 C# 中似乎没有等效的类,那么我应该在这里使用哪些(流?)类?或者流不是实现这个的正确方法吗?也许我最好使用 Queue
来代替?
谢谢
I am having some hard time understanding how to work with streams in C#.
I plan to have a class of this form:
class Pipe {
public void PutChar(char c) { ... }
public char GetChar() { ... }
}
The idea is that one thread will put chars in this Pipe
through its PutChar()
method, and later on other thread will make use of GetChar()
to get the chars that are in Pipe
.
In Java I'd make use of PipedReader
and PipedWriter
classes. There seem to be no equivalent classes in C#, so which (stream?) classes should I use here? Or aren't streams the correct way of implementing this? Maybe I'd be better off using a Queue
, instead?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为您想要跨线程通信,并且您不想使用上面答案中提到的任何 NamedPipes,而不是
1 - 您可以创建生产者消费者队列。
2-如果您使用的是.net 4.0,则可以使用ConcurrentQueue。
Because you want to communicate across threads and you don't want to use any NamedPipes as mentioned in above answers than
1- You can create Producer Consumer Queue.
2- If you are using .net 4.0 than ConcurrentQueue can be used.
在 System.IO.Pipes 命名空间中查找可以流式传输到的类管道。但是,您可能需要考虑使用 WCF ://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx" rel="nofollow">NetNamedPipeBinding 用于在应用程序中实现管道。
Look in the System.IO.Pipes namespace for classes that can stream to pipes. However, you may want to consider WCF using NetNamedPipeBinding for implementing pipes in your application.
如果您使用 .NET 4.0,请查看 BlockingCollection 和任务并行库。这两者结合在一起创建了一种使用任务跨线程移动数据的好方法。
MSDN 上的示例代码 显示了您需要执行的所有操作。
If you are using .NET 4.0 take a look at the BlockingCollection and the Task Parallel Library. Those two put together create a great way to move data across threads using Tasks.
Example code on MSDN shows everything you need to do.
查看 NamedPipe。另请查看这篇文章。
Take a look at the NamedPipe's. Also take a look at this post.
StreamReader & StreamWriter 与 PipedReader 和 PipedReader 非常相似。管道作家。如果你声明一个 MemoryStream 来保存缓冲区,你就可以实现它。
下面是一个快速代码示例,它可以满足您的需求。
StreamReader & StreamWriter are very similar to PipedReader & PipedWriter. If you declare a MemoryStream to hold the buffer you can implement it.
A quick code sample is below which may do what you are looking for.