-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
MultithreadingExample.cs
86 lines (77 loc) · 2.3 KB
/
MultithreadingExample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
namespace HelloDotNetGuide.异步多线程编程
{
/// <summary>
/// C#实现多线程的四种方式
/// </summary>
public class MultithreadingExample
{
/// <summary>
/// 使用 Thread 类
/// </summary>
public static void ThreadMethod()
{
var newThread = new Thread(WorkerMethod);
newThread.Start();
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"ThreadMethod 主线程开始工作:{i}");
Thread.Sleep(100);
}
}
/// <summary>
/// 使用 ThreadPool 类
/// </summary>
public static void ThreadPoolMethod()
{
ThreadPool.QueueUserWorkItem(o => WorkerMethod());
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"ThreadPoolMethod 主线程开始工作:{i}");
Thread.Sleep(100);
}
}
/// <summary>
/// 使用 Task 类
/// </summary>
public static void TaskMethod()
{
Task.Run(() => WorkerMethod());
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"TaskMethod 主线程开始工作:{i}");
Task.Delay(100).Wait();
}
}
/// <summary>
/// 使用 Parallel 类
/// </summary>
public static void ParallelMethod()
{
Parallel.Invoke(WorkerMethod, WorkerMethodOther1, WorkerMethodOther2);
}
private static void WorkerMethod()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethod 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}
private static void WorkerMethodOther1()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethodOther1 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}
private static void WorkerMethodOther2()
{
for (int i = 0; i < 8; i++)
{
Console.WriteLine($"WorkerMethodOther2 辅助线程开始工作:{i}");
Thread.Sleep(100);
}
}
}
}