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
294 views
in Technique[技术] by (71.8m points)

c# - be notified when all background threadpool threads are finished

I have a scenario when I start 3..10 threads with ThreadPool. Each thread does its job and returns to the ThreadPool. What are possible options to be notified in main thread when all background threads have finished?

Currently I'm using a homegrown method with incrementing a variable for each of created threads and decrementing it when a background thread is about to finish. This works just fine, but I was curious if there are better options.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Decrementing a variable (between threads) is a little bit risky unless done with Interlocked.Decrement, but that approach should be fine if you have the last thread (i.e. when it gets to zero) raise an event. Note that it would have to be in a "finally" block to avoid losing it in the case of exceptions (plus you don't want to kill the process).

In "Parallel Extensions" (or with .NET 4.0), you might also look at the Parallel.ForEach options here... that might be another way of getting everything done as a block. Without having to watch them all manually.


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

...