3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
因為經常會需要寫 C# 的多執行緒,每次在用到時都需要 google 或查以前的 code。久了發現有許多每次寫多執行緒會用的類別及方法,故整理成一包以利未來直接取用。因僅為個人筆記用,故本篇不多做解釋,唯加上一些註記以利讀者了解。依然附上 github 供讀者下載玩玩看。 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 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提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦