C Sharp

From David's Wiki
Revision as of 12:46, 20 August 2019 by David (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)


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();
  }
}