.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda LINQ Parse Path Process Property Regex Replace Sort Split Static StringBuilder Substring Switch Tuple


C#: .NET
Threads

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,
even with these classes,
is difficult.


Example. How can you use the Thread type in a C# program? This console program creates two instances of the Thread type and uses the ThreadStart class to specify their target methods A and B.

ThreadStartParameterizedThreadStart

Next:The threads are started and then they are joined. The two threads each run for a certain number of milliseconds.

JoinJoin objects together

Thread A:This thread starts first. It terminates after 100 milliseconds, a tenth of a second.

Thread B:This thread starts second. It ends after 1 second has elapsed. It prints B to the Console.

Console
Based on:

.NET 4.5

C# program that uses threading constructs

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

A
B

BackgroundWorker

BackgroundWorker. A good way 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 directly using threads.

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. The ThreadPool type provides built-in functionality.

ThreadPoolThreadPool.SetMinThreads
Lock-keyword

Lock. We show how to use the lock statement in the C# language. It also relates the Theory of Relativity to concurrent programs. The lock statement is a simplified syntax for Monitor method calls.

LockProgramming tip

Volatile:The volatile modifier ensures a field is used in a thread-safe way. This modifier can eliminate the need for lock statements.

Volatile

Interlocked:The Interlocked type provides a way to change or compare a value in an atomic way.

Interlocked
Mutex-type

Mutex. 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. We use Mutex to create a single-instance program.

Mutex

Tip:Mutex can be used in other program contexts, but generally the lock-keyword and the async and await keywords are clearer.


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.SleepSleep

SpinWait:With Thread.SpinWait, your computer can wait too, doing computationally intensive loops. This is a long-running loop.

Caution:Please don't expect me to pay your electricity bill if you use SpinWait. The point of SpinWait appears to be to waste electricity.

SpinWait
Async, await

Async, await. The .NET Framework 4.5 added the async and await keywords. Async modifies a method. It indicates a method can be asynchronously run. The await keyword waits for an async method to return. It is used within an async method.

Async, Await

Tip:Async and await make some threading patterns easier to implement. But they require planning and a careful design.


Note

Process. A process is separate at the level of the operating system. It can contain multiple threads. We can use separate processes instead of separate threads. This can move some of the complexity to the operating system.

Process
Framework: NET

Summary. Multiple threads can be executed in one process. As an alternative to using multiple threads, you can use multiple processes. Please also check out the Process type. Threading introduces extra complexity into programs.