Leo
Leo

Visual Studio C# 關於我寫 multi-thread 的起手式:Thread、ManualResetEvent、ConcurrentQueue

private static System.Collections.Concurrent.ConcurrentQueue<byte[]> _fifo = null;
private static System.Threading.ManualResetEvent _pauseEvent = null;
private static System.Threading.Thread _thread = null;

/// <summary>
/// 使用 Thread 創建多執行緒避免鎖住 UI
/// 使用 ManualResetEvent 控制 執行緒的運作
/// 使用 ConcurrentQueue 令多執行緒可以安全的共用資料
/// </summary>
/// <param name="args"></param>
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);
}

原文連結Leo Studio

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论