claws
claws

Reputation: 54100

How do I call a method when all threads (backgroundWorkers) are done with their jobs in .NET

I'm using C# .NET. Its a GUI application. When user clicks a button work is assigned to 4 different background workers. Each take different amount of time and the end result is they populate some variables.

I need to call a method which operates on these end results of each bgwoeker and gives the final output. How to accomplish this?

Problem here is to be sure that all bgworkers are done with their job.

Upvotes: 1

Views: 134

Answers (3)

mrwayne
mrwayne

Reputation: 637

1) If you are actually performing work that you expect to complete, do not use a background worker, use a proper thread or as above, use the thread pool.

2) See manual reset event example [http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx][1]

alternatively, use .net 4 and just use parallel linq, easy!

IEnumerable<myDelegate> delegates;
delegates.AsParallel().ForEach(adelegate => adelegate());

Done!

Edit: If i missed the purposed of your background threads is to stop the GUI locking up, then i would probably just launch a new thread, execute the tasks one after the other, and just use a single manual reset event. Of course, it really depends on what your requirements are.

Upvotes: 1

TcKs
TcKs

Reputation: 26632

You can encapsulate this feature in one class:

public class Synchronizer {
    private List<Action> workers = new List<Action>();
    public List<Action> Workers { get { return workers; } }

    public void Run( Action callBackOnDone ) {
        var workers Workers.ToArray();
        object syncRoot = new object();
        int counter = workers.Length;
        foreach( var worker in workers ) {
            ThreadPool.QueueUserWorkItem( ()=> {
                try { worker(); }
                finally {
                    lock(syncRoot) {
                         counter--;
                         if ( counter <= 0 ) {
                             callBackOnDone();
                         }
                    }
                }
            } );
        }
    }
}

Upvotes: 0

Andrew
Andrew

Reputation: 1102

You can make counter and check it from RunWorkerCompleted eventhandler of each BackgroundWorker or check state of other 3 Backgroundworkers from RunWorkerCompleted of each Backgroundworker.

Upvotes: 3

Related Questions