search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[C#] 一些關於我寫 multi-thread 的起手式|Thread、ManualResetEvent、ConcurrentQueue | 不只是個工程師

因為經常會需要寫 C# 的多執行緒,每次在用到時都需要 google 或查以前的 code。久了發現有許多每次寫多執行緒會用的類別及方法,故整理成一包以利未來直接取用。
因僅為個人筆記用,故本篇不多做解釋,唯加上一些註記以利讀者了解。
依然附上 github 供讀者下載玩玩看。

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
private static System.Collections.Concurrent.ConcurrentQueue<byte[]> _fifo = null;
private static System.Threading.ManualResetEvent _pauseEvent = null;
private static System.Threading.Thread _thread = null;

///
/// 使用 Thread 創建多執行緒避免鎖住 UI
/// 使用 ManualResetEvent 控制 執行緒的運作
/// 使用 ConcurrentQueue 令多執行緒可以安全的共用資料
///
///
private static void Main(string[] args)
{
_thread = new System.Threading.Thread(MyThreadMethod); // 初始化 "Thread"
_pauseEvent = new System.Threading.ManualResetEvent(false); // 初始化 "ManualResetEvent" 並預設為 暫停 (false)
_fifo = new System.Collections.Concurrent.ConcurrentQueue<byte[]>(); // 初始化 "安全執行緒的先進先出 (FIFO) 集合"

_thread.Start();

Task.Factory.StartNew(MyTestMethod);

READ_CMD:
var ck = Console.ReadKey(true);
if (ck.Key == ConsoleKey.S)
{
_pauseEvent.Set(); // 釋放 "ManualResetEvent"
}
else if (ck.Key == ConsoleKey.R)
{
_pauseEvent.Reset(); // 鎖住 "ManualResetEvent"
}
goto READ_CMD;
}

private static void MyTestMethod()
{
do
{
_pauseEvent.WaitOne(System.Threading.Timeout.Infinite);
var result = _fifo.TryDequeue(out var array);
if (result && array != null)
{
Console.Write($"{nameof(array)}: ");
for (var idx = 0; idx < array.Length; idx++)
{
Console.Write($"{array[idx]} ");
}
}
Console.WriteLine();
System.Threading.Thread.Sleep(800);
} while (true);
}

private static void MyThreadMethod()
{
var random = new Random();
do
{
_pauseEvent.WaitOne(System.Threading.Timeout.Infinite);
var array = new byte[10];
random.NextBytes(array);
_fifo.Enqueue(array);
Console.Write($"{nameof(array)}: ");
for (var idx = 0; idx < array.Length; idx++)
{
Console.Write($"{array[idx]} ");
}
Console.WriteLine();
System.Threading.Thread.Sleep(500);
} while (true);
}

完整的 sample code 我放在 github 上了,歡迎下載玩玩看!

github sample code:https://github.com/leoli-git/MySampleCode/tree/main/MyMultiThread



熱門推薦

本文由 leotalk-engineerlifecom 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦