.Net prevent 2 parallel services processing the same command

I want to deploy an Windows services in parallel for redundancy and load balancing purposes.

How can i be sure that when the client sends a request to both of these services, that only 1 of them process the actual call?


When the client or other services sends a message to start a manufacturing process, both of these services will recieve that request. I want to make sure that only one of those services processes this request, so that manufacturing process do not get started twice!

Do they need to able to talk to themself? Is there a possibility to sync those services?

Which is the most elegant/robust way of handling this problem?

2 answers

  • answered 2020-09-24 11:39 Tom Ruyter

    Look into using a mutex to allow both services to only pick up a message once.

    Mutex Description C#

    Although, you'll need to make sure this can work in the way you want. this can help schedule between application processes and boundaries, but if this is deploy to two different machines, or Cloud services, the Mutex isn't going to work.

    for that you'll need to figure out another of communicating across the applications, usually using a database or a MSMQ to create a message queue that you can pop messages off as you need them from each service.

  • answered 2020-09-24 12:13 Pino De Francesco

    The safest way, and also the best practice, for your example, would be to retrieve (not to peek) messages from a queue leveraging MSMQ. This gives you a clear explanation of the use case: https://docs.microsoft.com/en-us/previous-versions/windows/desktop/msmq/ms706253(v=vs.85)