C Sharp: Difference between revisions

From David's Wiki
(Created page with " ==Multithreading== ===Theadpool=== C# has a convenient [https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool?view=netframework-4.8 TheadPool] class in th...")
 
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 {
Line 28: Line 27:
       });
       });
     }
     }
     // Blocking wait.
     // Blocking wait.
     finishedHandle.WaitOne();
     finishedHandle.WaitOne();

Revision as of 12:46, 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();
  }
}