Question: Rough context: messaging system, `Communicator` sends messages (increases field `_messagesInTransmission`), receives ACK or NAK on another thread (decreases `_messagesInTransmission`).

If an instance of Communicator is disposed it should stop its underlying transport instance as soon as `_messagesInTransmission` hits zero the next time.

How to implement this in a thread-safe way?

```
public void Dispose()
{
    _state = State.Stopping; // immediately change state in order to prevent additional messages to be sent

    // TODO: wait for _messagesInTransmission to become zero
}

```

Does the .NET framework support me with this task?

---

A simple solution would be a while(\_mIT != 0) loop and some Thread.Sleep, however, I want to write more appealing code if possible.

Answer: 
You really don't want to do this on `Dispose()`.

Consider a situation where your receiving application crashes and never ACK/NACK's one of the messages. You'll never receive enough responses to zero the counter, and when the dispose is called, possibly during GC or a `using(...){...}` block, it's going to hang indefinitely.

I'd suggest moving this functionality to another method which is called `OnStop()`.

And just keep your `Dispose()` method for cleaning up resources, closing connections etc...
How vital is it that those messages are sent? Generally, you should have some kind of `Stop()` method on your class to do what you are looking for. Doing this kind of action in the Dispose method is a little dangerous because Dispose methods shouldn't have the potential to throw errors or hang.

Also, make sure your worker thread is created with `IsBackground` set to true. That way, when your application closes, it is certain to complete as well.