Write First Threading App In C#

if you've never created a multi-threaded app, this is basic introduction of threading in .NET using C#.

The Thread class represents a thread and provides functionality to create and manage a thread’s lifecycle, and its properties such as status, priority, state.

The Thread class is defined in the System.Threading namespace must be imported before you can use any threading related types.

using System.Threading;

The Thread constructor takes a ThreadStart delegate as a parameter and creates a new thread. The parameter of the ThreadStart is the method that is executed by the new thread. Once a thread it created, it needs to call the Start method to actually start the thread.

The following code snippet creates a new thread, workerThread that will execute code in the Print method.

// Create a secondary thread by passing a ThreadStart delegate

Thread workerThread = new Thread(new ThreadStart(Print));

// Start secondary thread

workerThread.Start();

The Print method is listed below that can be used to execute code to do some background or foreground work.

staticvoid Print()

{

}

Let’s try it.

Open Visual Studio. Create a new .NET Core console project. Delete all code and copy and paste (or type) the code in Listing 1.

using System;

using System.Threading;

class Program

{

staticvoid Main()

{

// Create a secondary thread by passing a ThreadStart delegate

Thread workerThread = new Thread(new ThreadStart(Print));

// Start secondary thread

workerThread.Start();

// Main thread : Print 1 to 10 every 0.2 second.

// Thread.Sleep method is responsible for making the current thread sleep

// in milliseconds. During its sleep, a thread does nothing.

for (int i=0; i< 10; i++)

{

Console.WriteLine($"Main thread: {i}");

Thread.Sleep(200);

}

Console.ReadKey();

}

/// <summary>

/// This code is executed by a secondary thread

/// </summary>

staticvoid Print()

{

for (int i = 11; i < 20; i++)

{

Console.WriteLine($"Worker thread: {i}");

Thread.Sleep(1000);

}

}

}

Listing 1.

The code of Listing 1, the main thread prints 1 to 10 after every 0.2 seconds. The secondary thread prints from 11 to 20 after every 1.0 second. We’re using the delay for the demo purpose, so you can see live how two threads execute code parallelly.