Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - Get count of current active Tasks spawned by a multithreaded application


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...