C Sharp
Multithreading
Theadpool
C# has a convenient TheadPool class in the System.Threading namespace.
class TestClass {
static void Main(string[] args) {
int numberOfTasks = 10;
int tasksRemaining = 10;
// This is similar to a mutex.
ManualResetEvent finishedHandle = new ManualResetEvent(false);
for (int i = 0; i < numberOfTasks; i++) {
int j = i;
ThreadPool.QueueUserWorkItem(_ => {
try {
// Do something time consuming or resource intensive.
// Do not use i here. You can use j instead.
} catch (System.Exception e) {
// Print Stack Trace
} finally {
if (Interlocked.Decrement(ref tasksRemaining) == 0) {
finishedHandle.Set();
}
}
});
}
// Blocking wait.
finishedHandle.WaitOne();
}
}