问题描述
我有一个Windows服务,处理工作。在此服务的作业是的动作,例如一个序列:
I have a Windows service that processes jobs. A job in this service is a sequence of actions, such as:
A - > B - >ç - >ð - >电子
每个任务应该是完全独立于其他工作。当前的实现处理其自己的线程的每个作业(在此情况下,新System.Threading.Thread
),效果很好,大部分时间。然而,事实证明,对B的动作不是线程安全的,并且两个线程不应该处理对B的动作在同一时间。如果两个线程试图完成对B的动作的同时,奇怪的结果或错误有时会发生。请注意,其他动作可以同时由多个作业不受有害影响地执行。
Each job is supposed to be completely independent from other jobs. The current implementation processes each job on its own thread (in this case, new System.Threading.Thread
), which works well most of the time. However, it turns out that the B action is not thread-safe and two threads should not process the B action at the same time. If two threads try to perform the B action at the same time, strange results or errors are sometimes occurring. Note that the other actions may be executed concurrently by multiple jobs without any ill effects.
而不是试图重新实现对B的行动以线程安全的方式(这我预计将需要大量的资源来实现和测试),我想只限定各B动作单线程在时间
Rather than attempting to re-implement the B action in a thread-safe manner (which I anticipate would require a large amount of resources to implement and test), I would like to just limit each the B action to a single thread at a time.
现在显而易见的初步解决方案,我是可以把一个锁定
各地对B的动作,这无疑将限制到单个线程。但是,看来这个解决方案将不能保证所有等待的线程将有机会来处理对B的动作。这是因为线程不能保证排队在FIFO或一致的方式。我喜欢这种感觉理论上可以导致线程饥饿。因此,我不舒服实施此解决方案。
Now the obvious initial solution to me was be to put a lock
around the B action, which would certainly limit it to a single thread. However, it appears that this solution would not guarantee that all waiting threads will get a chance to process the B action. This is because threads are not guaranteed to queue up in a FIFO or consistent manner. I feel like this could theoretically lead to thread starvation. Thus, I am not comfortable implementing this solution.
所以我的问题是我怎么能实现一个更好的(可能是FIFO)的工作在.NET中的队列,保证所有的作业将通过B动作做到最好的,一个接一个?的
我目前的想法是,我可以保持某种形式的经理,其任务是从队列中拉出工作线程,并执行它当B的动作是明确的线程。 (也许是我描述实现我自己的调度?),但它似乎像,可能是相当粗糙,也许.NET(我使用.NET 4.0)具有更好的工具在其图书馆此方案。
My current thought is that I could maintain a some kind of "manager" thread whose job is to pull a job thread from a queue and execute it when the B action is clear. (Perhaps I am describing implementing my own scheduler?) But it seems like that may be rather crude and that perhaps .NET (I'm using .NET 4.0) has better tools in its library for this scenario.
推荐答案
你是什么可能是后沿的创造者 - 消费者模式的行的东西。 这个计算器帖子有一个很好的实现阻塞队列中。所以,你可以有多个线程添加的东西给它,而只是一个线程永远读的东西从它(它会阻止当队列为空)
What you're likely after is something along the lines of a creator-consumer pattern. this stackoverflow post has a nice implementation of a blocking queue. So you can have multiple threads add things to it, and just one thread forever reading things from it (and it'll block when the queue is empty)
这篇关于怎样才能实现.NET作业队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!