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...
The "thread safe" way to do it (and is how things like `FileStream` handle it) is to have a `Flush()` method that is blocking that writes out all the pending writes. Once you have that you just need to have `Flush()` be called inside the `Dispose()` method.

Now this will cause `Dispose()` to block, but you know what? We want dispose to block! If you do not block on dispose while work is still being done the last reference to the object could be released (very likely to happen inside a `using` block) and your object will be eligible for garbage collection before it is done processing.