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++) {
      int j = i;
       ThreadPool.QueueUserWorkItem(_ => {
       ThreadPool.QueueUserWorkItem(_ => {
         try {
         try {
           // Do something time consuming or resource intensive.
           // Do something time consuming or resource intensive.
          // Do not use i here. You can use j instead.
         } catch (System.Exception e) {
         } catch (System.Exception e) {
           // Print Stack Trace
           // Print Stack Trace

Revision as of 13:27, 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++) {
      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();
  }
}