Languages
[Edit]
EN

C#/.NET - create thread

5 points
Created by:
Marcin
15710

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

There are few ways how to do it but this example is focused on simple approach based on Thread class.

Simple steps:

  1. create new Thread object passing function as constructor argument,
  2. run thread with Thread.Start() method.

Simple 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);
			}
		});

		thread.Start();
	}
}

Output (Linux Mono):

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

Where:

  • Thread class - creates new thread object
  • Thread.Start method - runs created thread
  • Thread.Sleep method - sleeps thread execution for 1 second (1000 milliseconds)

References

  1. Thread Class - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join