EN
C#/.NET - create thread
5
points
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:
- create new
Thread
object passing function as constructor argument, - 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 objectThread.Start
method - runs created threadThread.Sleep
method - sleeps thread execution for 1 second (1000 milliseconds)