Friday, 20 February 2009

Multithreading and Locking in C#

The main purpose of using multithreading in applications is to improve performance.

Process and Thread

  • An application, an executing program, consists of one or more processes.
  • A process, in the simplest terms, is an executing program.
  • One or more threads run in the context of the process
  • Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.
  • The System.Threading namespace contains various types that allow you to create multithreaded applications.
  • The Thread class is perhaps the core type, as it represents a given thread.
  • If you wish to programmatically obtain a reference to the thread currently executing a given member, simply call the static Thread.CurrentThread property.

ThreadPool

The ThreadPool class provides your application with a pool of worker threads that are managed by the system, allowing you to concentrate on application tasks rather than thread management.

  • By default, the limit is 25 worker threads per CPU and 1,000 I/O completion threads.
  • You use the thread pool by calling ThreadPool.QueueUserWorkItem from managed code (or CorQueueUserWorkItem from unmanaged code).
  • There is only one thread pool per process.

Application Domain

  • Application domains, which are represented by AppDomain objects, help provide isolation, unloading, and security boundaries for executing managed code.
  • Multiple application domains can run in a single process
  • Several threads can belong to a single application domain
  • Application domains are created using the CreateDomain method.
  • AppDomain instances are used to load and execute assemblies (Assembly).
  • Threads are free to cross application domain; however, at any given time, a thread executes in a single application domain: AppDomain ad = Thread.GetDomain();

Thread Synchronization:

  • lock{} does the work of Monitor.Enter and Monitor.Exit when we need to lock a section based on an object
  • The object that we want to lock by must be a reference type not a value type. Every object has one field called SyncBlock and only one thread is allowed to own this field. lock keyword works with this field.
  • Don't use Type for your lock; it may cause having deadlocks

More Info

No comments: