In the comments, I is told that I should avoid thread.sleep (), all right, let's try this:
1. You could wrap the Parallel.ForEach within a task and manually add your Completedcallback ()
Public Task Doworkasync (doworkcompletedcallback completedcallback) { return Task.Factory.StartNew ( { Parallel.ForEach //callcallback manually Completedcallback (); });}
2. Use ContinueWith
Task.Factory.StartNew ( { //do work } ). ContinueWith (completedcallback);
3. You could assign callback in the caller, it ' s the same as 2.
Task NewTask = Task.Factory.StartNew ( { //do work}); Newtask.continuewith (oncompleted);
4. Consumer-publisher Patterns
Producer Consumer problem
Assume you has a huge object hosting messages Concurrentlist<string>, task pushes a message ' oncompleted ' to the OB Ject, on the other side, a listener subscribes the message, once a oncompleted received, it'll execute the continuation.
C # Multithreading multiple threads handles one task and then executes the rest