Updated 7/17/2018
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.
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.
-
- Thread workerThread = new Thread(new ThreadStart(Print));
-
- workerThread.Start();
The Print method is listed below that can be used to execute code to do some background or foreground work.
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
- {
- static void Main()
- {
-
- Thread workerThread = new Thread(new ThreadStart(Print));
-
- workerThread.Start();
-
-
-
-
- for (int i=0; i< 10; i++)
- {
- Console.WriteLine($"Main thread: {i}");
- Thread.Sleep(200);
- }
-
- Console.ReadKey();
- }
-
-
-
-
- static void 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.