I have a connection class which has several async methods such as SendText, SendImage etc.
The connection class has a Disconnect method, and when it is called I have to be careful not to start changing the inner state of the class before all async methods have completed execution.
I believe a good way to achieve this is to simply keep a running total of the number of operations in execution, and then when I want to Disconnect I can simply set Disconnecting = true and then wait for the count to reach 0
I’m thinking of something along the lines of this
class ReferenceCounter
{
void Increment();
void Decrement();
async Task WaitForCounterToReachZero();
}
Then when an async operation starts I could do
refCounter.Increment();
When it ends
refCounter.Decrement();
and inside the Disconnect method
disconnecting = true;
taskCancellationSource.Cancel();
await refCounter.WaitForCounterToReachZero();
Cleanup();
Are there any built in .NET classes like this?
Or more importantly for me, is there a better way of doing this?
If it was synchronous code it would be as simple as
lock (thisLock)
{
while (counter > 0)
Monitor.Wait(thisLock);
}
I just found the built in CountdownEvent class which does the same thing, but it has no async Wait method nor does it have any events, so I’d have to block.
Well, assuming you’ll never increment again after you make it 0, you could do something like this:
Then you can await
someLatch.Task. Alternatively, you could make the latch itself awaitable:You should probably consider how you want to guard against the “count rises after getting down to 0” aspect thuogh – think about what you’d want it to do. (In the code above, once the TCS’s value has been set, further awaits will complete immediately.)