Languages
[Edit]
EN

C#/.NET - create thread

8 points
Created by:
Marcino
600

In this short article, we want to show you how to create and run a new thread in C# / .NET.

Note: there are different ways how to create threads but in this article we use simple approach based on Thread class.

Quick solution:

// using System.Threading;

Thread thread = new Thread(() =>
{
    // put some source code here ...
});

thread.Start();

 

Practical example

In this section new Thread object is created for logic passed in the constructor argument. Created thread is not run until Start() method is called. Thread is running until indicated logic does not end execution.

Source code:

using System;
using System.Threading;

public class Program
{
	public static void Main(string[] args)
	{
		Thread thread = new Thread(() =>
		{
			for (int i = 1; i <= 5; ++i)
			{
				Console.WriteLine("Iteration: " + i);
				Thread.Sleep(1000); // sleeps created thread for 1 second
			}
		});

		thread.Start();
	}
}

Output (Linux Mono):

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Hint: to stop thread Thread Abort() method can be used too but it requires knowledge about consequences.

 

References

  1. Thread Class - Microsoft Docs
  2. Thread.Start Method (System.Threading) - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# - Thread Class

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join