Threading

Download c# eBook

Remarks

A thread is a part of a program that can execute independently of other parts. It can perform tasks simultaneously with other threads. Multithreading is a feature that enables programs to perform concurrent processing so that more than one operation can be done at a time.

For example, you can use threading to update a timer or counter in the background while simultaneously performing other tasks in the foreground.

Multithreaded applications are more responsive to user input and are also easily scalable, because the developer can add threads as and when the workload increases.

By default, a C# program has one thread - the main program thread. However, secondary threads can be created and used to execute code in parallel with the primary thread. Such threads are called worker threads.

To control the operation of a thread, the CLR delegates a function to the operating system known as Thread Scheduler. A thread scheduler assures that all the threads are allocated proper execution time. It also checks that the threads that are blocked or locked do not consume much of the CPU time.

The .NET Framework System.Threading namespace makes using threads easier. System.Threading enables multithreading by providing a number of classes and interfaces. Apart from providing types and classes for a particular thread, it also defines types to hold a collection of threads, timer class and so on. It also provides its support by allowing synchronized access to shared data.

Thread is the main class in the System.Threading namespace. Other classes include AutoResetEvent, Interlocked, Monitor, Mutex, and ThreadPool.

Some of the delegates that are present in the System.Threading namespace include ThreadStart, TimerCallback, and WaitCallback.

Enumerations in System.Threading namespace include ThreadPriority, ThreadState, and EventResetMode.

In .NET Framework 4 and later versions, multithreaded programming is made easier and simpler through the System.Threading.Tasks.Parallel and System.Threading.Tasks.Task classes, Parallel LINQ (PLINQ), new concurrent collection classes in the System.Collections.Concurrent namespace, and a new task-based programming model.

Related Examples

Stats

428 Contributors: 15
Monday, April 17, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook