Monday, 12 November 2007

Chapter 7, lesson 1: Threading.

Threading - performing multiple operations concurrently.

  • Thread class - to create + start threads.
  • ThreadState enumeration - e.g. ThreadState.Aborted.
  • create a thread - 1) create mthd which will run on thread - ret. void, no param.
  • 2) wrap mthd in ThreadStart delegate - ThreadStart operation = new ThreadStart(dispatcher);
  • 3) create thread - Thread theThread = new Thread(operation);
  • 4) start thread - theThread.Start();
  • Thread.Sleep - allows other threads to perform work.
  • Join() - makes app wait until a thread has completed.
  • ParamterizedThreadStart delegate - mthd signature has single param of type Object. Ret. void. In dispatcher(), test that obj passed in is of expected type.

Stopping Threads

  • Thread.Abort() - where dispatcher() doesn't catch ThreadAbortExeception(), thread stops at line currently executing when main thread calls Abort. Inconsistent termination point, irrespective of whether exception is caught.
  • BeginCriticalRegion, EndCriticalRegion - A critical region is a section of code that must be executed as if it were a single stmt. Any attempt to abort while within a critical region will have to wait until completion.

Execution Cnotext

  • Each thread has data associated with it - Security info (IPrincipal + thread ID), localization settings (e.g. culture thread is running in), txn info.
  • This contexct info is usually propogated to new threads.
  • default - execution context flows to helper threads.
  • ExecutionContext.SuppressFlow - can stop this - increases perf.

No comments: