Files
CSharp-learning/C# Full Course for free/16.multithreading.md
2026-01-13 05:13:08 +01:00

91 lines
1.6 KiB
Markdown

# multithreading
thread is an execution path of a program
we can use multiple threads to perform,
different taks of our program at the same time.
Current thread running is "main" thread
using System.Threading;
## Single Thread
```C#
// single Thread
using System.Threading;
Thread mainThread = Thread.CurrenThread;
mainThread.Name = "Main Thread";
Console.WriteLine(mainThread.Name);
```
### Timer Example
```C#
public static void CountDown()
{
for (int i = 10; i >=0; i--)
{
Console.WriteLine("Timer #1 : " + i + " seconds");
Thread.Sleep(1000)
}
Console.WriteLine("Timer #1 is complete !")
}
public static void CountUp()
{
for (int i = 0; i >=0; i++)
{
Console.WriteLine("Timer #2 : " + i + " seconds");
Thread.Sleep(1000)
}
Console.WriteLine("Timer #2 is complete !")
}
```
```C#
// Main
CountDown();
CountUp();
```
## multiple Thread
```C#
public static void CountDown()
{
for (int i = 10; i >=0; i--)
{
Console.WriteLine("Timer #1 : " + i + " seconds");
Thread.Sleep(1000)
}
Console.WriteLine("Timer #1 is complete !")
}
public static void CountUp()
{
for (int i = 0; i >=0; i++)
{
Console.WriteLine("Timer #2 : " + i + " seconds");
Thread.Sleep(1000)
}
Console.WriteLine("Timer #2 is complete !")
}
```
```C#
// Main
Thread thread1 = new Thread(CountDown);
Thread thread2 = new Thread(CountUp);
// if the function got a parameter
// use a lambda
// Thread thread1 = new Thread(() => CountDown("Thimer #1"));
thread1.start();
thread2.start();
CountDown();
CountUp();
```