Languages
[Edit]
EN

C#/.NET - create thread

5 points
Created by:
Marcin
2444

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

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍