C Sharp

Working with Threads

All creation and management of threads is achieved through use of the System.Threading.Thread class, so we'll start there.

AppDomain

In .NET, threads run in something called an AppDomain. You'll sometimes hear that an AppDomain is analogous to a Win32 process in that it offers many of the same benefits, including fault tolerance and the ability to be independently started and stopped. This is a good comparison, but the comparison breaks down in relation to threads. In Win32, a thread is confined to a single process, as you saw when I described context switching earlier. A thread in one process cannot invoke a method in a thread that belongs to another process. In .NET, however, threads can cross AppDomain boundaries, and a method in one thread can call a method in another AppDomain. Therefore, here's a better definition of an AppDomain: a logical process inside of a physical process.

The Thread Class

Most everything you do with threads you'll do using the Thread class. This section looks at using the Thread class to carry out basic threading tasks.

Creating Threads and Thread Objects

You can instantiate a Thread object in two ways. You've already seen one way: creating a new thread and, in that process, getting a Thread object with which to manipulate the new thread. The other way to obtain a Thread object is by calling the static Thread.CurrentThread method for the currently executing thread.