C Sharp: Difference between revisions

From David's Wiki
No edit summary
No edit summary
Line 15: Line 15:
     ManualResetEvent finishedHandle = new ManualResetEvent(false);
     ManualResetEvent finishedHandle = new ManualResetEvent(false);
     for (int i = 0; i < numberOfTasks; i++) {
     for (int i = 0; i < numberOfTasks; i++) {
       ThreadPool.QueueUserWorkItem(_ = > {
       ThreadPool.QueueUserWorkItem(_ => {
         try {
         try {
           // Do something time consuming or resource intensive.
           // Do something time consuming or resource intensive.

Revision as of 12:49, 20 August 2019


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++) {
      ThreadPool.QueueUserWorkItem(_ => {
        try {
          // Do something time consuming or resource intensive.
        } catch (System.Exception e) {
          // Print Stack Trace
        } finally {
          if (Interlocked.Decrement(ref tasksRemaining) == 0) {
            finishedHandle.Set();
          }
        }
      });
    }

    // Blocking wait.
    finishedHandle.WaitOne();
  }
}