在C#Queue实现 [英] Queue implementation in C#
问题描述
我处理的硬件资源,只能同时处理1命令。我要通过Web界面露出一些它的API函数,所以很明显有超过1命令将在同一时间被发送的好机会。我已经决定,他们提交排队时这些命令是为了确保串行处理的最佳方式。
I'm dealing with a hardware resource that can only handle 1 command at a time. I'm going to exposing some of it's API functions via a web interface, so obviously there's a good chance more than 1 command will get sent at a time. I have decided that queuing these commands when they're submitted is the best way to ensure serial processing.
我打算在静态类实现队列。 Web应用程序的代码隐藏通过调用相应的他们想要的命令的方法添加一个命令。我想调用方法等待,直到它得到了命令的输出,因此不需要异步神奇。
I'm planning on implementing the queue in a static class. The web app code-behind will add a command by calling a method corresponding to the command they want. I want the calling method to wait until it gets the output of its command, so no async magic is required.
-
我是这样做对吗?有没有更好的办法?
Am I doing this right? Is there a better way?
我如何开始在C#实现队列(我通常使用Java工作)?我想我需要某种形式的事件信号工作已添加和处理程序来启动队列处理...
How do I start implementing the queue in C# (I usually work with Java)? I assume I'll need some sort Event to signal a job has been added, and a Handler to initiate processing of the queue...
我使用的.NET Framework 4。
I'm using .NET Framework 4.
推荐答案
您可以使用 ConcurrentQueue
类的实现,并有一个专门的线程来处理项目在队列中。
You can use the ConcurrentQueue
class for your implementation and have a dedicated thread to process items in the queue.
有关等待的部分您可以使用的 的AutoResetEvent
,生产者事件实例传递给单例类的请求一起,然后调用的WaitOne( )
哪些块直至处理器已经发出信号,通过调用设置()
。
For the waiting part you can use an AutoResetEvent
, producers pass the event instance to the singleton class along with the request, then calls WaitOne()
which blocks until the processor has signaled processing is completed by calling Set()
.
这篇关于在C#Queue实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!