我应该使用消息队列来保证 Windows 服务一次只对一条记录进行操作吗?
刚刚看到一篇文章谈论消息队列。我有一个服务每 1 秒运行一个进程。该进程将名为“ProcessLock”的静态布尔值更改为 true。然后,该进程在执行之前检查该变量是否为 true:
if (!ProcessLock)
{
ProcessLock= true;
//dostuff
}
但是,如果该进程再次循环并在另一个线程进入括号之后但在将 bool 更改为 true 之前进入括号,那么我们会出现问题,因为里面的代码将开始对同一条记录进行两次操作。这种情况叫什么?我确定它有一个多线程术语吗?
不管怎样,真正的问题是我可以使用 MSMQ 来解决这个问题吗?一般是怎样的流程?
Just came across a article talking about message queuing. I have a service that runs a process every 1 seconds. The process changes a static bool called 'ProcessLock' to true. The process then checks to see if this variable is true before it executes like this:
if (!ProcessLock)
{
ProcessLock= true;
//dostuff
}
However if this process was to loop round again and enter the bracket just after another thread has entered after the bracket but before it has changed the bool to true then we would get a problem because the code inside would start to operate twice on the same records. What is this condition called? Im sure its got a multithreading term?
Anyway the real point is can I use MSMQ to get round this problem? Whats the process in general?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
消息传递通常用于确保可靠的交付并放松服务之间的时间耦合。
据我了解,您的服务每次执行时都会对相同的数据进行操作。在这种情况下,消息队列就没有多大帮助了;毕竟,可以并行处理多个消息。您可以将消息处理配置为在单个线程上运行(一次处理一条消息),但简单的锁可以更轻松地解决此问题。
另一方面,如果您可以创建工作项供您的服务处理,那么某种队列将是有益的。如果您不关心可靠性并且不需要进程间通信,它可以是简单的自制
Queue
,没有复杂的消息传递基础设施。Messaging is usually used to ensure reliable delivery and to relax temporal coupling between services.
As I understand your service is operating on the same data each time it is executed. In that case, message queue wouldn't help you much; after all, there can be multiple messages being processed in parallel. You could configure your message handling to run on a single thread (handle one message at a time), but simple lock could solve this problem more easily.
On the other hand, if you could create work items for your service to process, some sort of queue would be beneficial. It can be simple home grown
Queue<WorkItem>
, with no complicated messaging infrastructure if you don't care about reliability and don't need inter-process communication.