TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Threads: Using Thread Type

These C# articles show how to implement threads in programs. They cover the Thread type in System.Threading.

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.

Join

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

Lock

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

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

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

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf