C# Thread Overview

.NET Thread

Threads illustration

Threads improve performance. They move computations to a separate logical processor. They are handled in the .NET Framework with classes from the base class library. Multithreading is difficult. Implementing complex thread behaviors can be nearly impossible. Threading is thus often discouraged unless unavoidable.

Just as we can make our programs modular by organizing models in terms of objects with separate local state, it is often appropriate to divide computational models into parts that evolve separately and concurrently. Abelson & Sussman, p. 297

Example

Question and answer

How can you use the Thread type in the C# programming language? This introductory program creates two instances of the Thread type and uses the ThreadStart class to specify their target methods A and B. The threads are started and then they are joined.

Program that uses threading constructs [C#]

using System;
using System.Threading;

class Program
{
    static void Main()
    {
	Thread thread1 = new Thread(new ThreadStart(A));
	Thread thread2 = new Thread(new ThreadStart(B));
	thread1.Start();
	thread2.Start();
	thread1.Join();
	thread2.Join();
    }

    static void A()
    {
	Thread.Sleep(100);
	Console.WriteLine('A');
    }

    static void B()
    {
	Thread.Sleep(1000);
	Console.WriteLine('B');
    }
}

Output
    (The threads terminate after 0.1 and 1.0 seconds.)

A
B

BackgroundWorker

One of the best ways to implement simple threading in Windows Forms programs is to use the BackgroundWorker class. This results in error-free and reliable threading. The class lacks some features you can implement by using threads directly.

BackgroundWorker

ThreadPool

With the ThreadPool, you can execute many different threads in parallel and have the system recycle them as soon as possible. This is an ideal way to start many short-lived jobs.

ThreadPool ThreadPool.SetMinThreads

Lock

Lock keyword

We show how to use the lock statement in the C# language. Also, it relates the theory of relativity to concurrent programs. The lock statement is a simplified syntax for Monitor method calls.

Lock

ThreadStart

You can start threads by passing an instance of the ThreadStart type in the C# language. We provide examples for starting threads in this way—with and without parameters to the thread.

ThreadStart ParameterizedThreadStart

Join

Join objects together

When you join a thread, the current thread stops and waits for the target thread to exit. You can use Join to ensure all threads are completed at a certain point in your program.

Join

Volatile

The volatile modifier in the C# language provides a way for you use ensure a field is used in a thread-safe way. This modifier can eliminate the need for lock statements or other, more verbose threading constructs.

Volatile

Interlocked

The Interlocked type provides a way to change or compare a value in an atomic way: this means the read and write operations are a single step and nothing can interrupt them during normal operation of the program.

Interlocked

Mutex

Mutex type

Continuing on, the .NET Framework provides the Mutex type in the System.Threading namespace. This type is used to synchronize processes and threads within a single process.

Mutex

Sleep

By using the Sleep method, you can pause a thread and not have it incur any actual CPU usage. Instead, the thread is simply delayed for a certain amount of time, measured in milliseconds.

Thread.Sleep

SpinWait

Everyone loves waiting. With Thread.SpinWait, your computer can wait too, doing computationally intensive loops. This is for when writing an infinite loop is too challenging.

Thread.SpinWait

Note: Please don't expect me to pay your electricity bill if you use SpinWait (or otherwise). The whole point of SpinWait appears to be to waste electricity.

Summary

.NET Framework information

Multiple threads can be executed in one process. As an alternative to using multiple threads, you can simply use multiple processes. Please check out the Process type in the .NET Framework.

Process
.NET