If you want a thread-safe counter to check the number of active tasks you can use an int _counter field and Interlocked.Increment(ref _counter)/Interlocked.Decrement(ref _counter).
int _counter
Interlocked.Increment(ref _counter)
Interlocked.Decrement(ref _counter)
Remember to increment as the first line in a try block decrement in a finally block so that you don't lose any calls to either if an exception is raised.
try
finally
https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.increment?view=net-5.0
https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.decrement?view=net-5.0
2.1m questions
2.1m answers
60 comments
57.0k users