EN
C#/.NET - create thread
8 points
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:
xxxxxxxxxx
1
// using System.Threading;
2
3
Thread thread = new Thread(() =>
4
{
5
// put some source code here ...
6
});
7
8
thread.Start();
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:
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
Thread thread = new Thread(() =>
9
{
10
for (int i = 1; i <= 5; ++i)
11
{
12
Console.WriteLine("Iteration: " + i);
13
Thread.Sleep(1000); // sleeps created thread for 1 second
14
}
15
});
16
17
thread.Start();
18
}
19
}
Output (Linux Mono):
xxxxxxxxxx
1
Iteration: 1
2
Iteration: 2
3
Iteration: 3
4
Iteration: 4
5
Iteration: 5
Hint: to stop thread
Thread
Abort()
method can be used too but it requires knowledge about consequences.