C#使用執行緒安全佇列ConcurrentQueue處理資料

字母搬运工-Hauk發表於2024-10-09
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp10
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test();
 
            Console.ReadKey();
        }
 
        private static void Test()
        {
            ConcurrentQueue<long> numQueue = new ConcurrentQueue<long>();
 
            Task.Factory.StartNew(() =>
            {
                do
                {
                    numQueue.Enqueue(DateTime.Now.Ticks);
                    Thread.Sleep(500);
                } while (true);
            });
            Task.Factory.StartNew(() =>
            {
                do
                {
                    numQueue.Enqueue(DateTime.Now.Ticks);
                    Thread.Sleep(1000);
                } while (true);
            });
            Task.Factory.StartNew(() =>
            {
                do
                {
                    long result = 0;
                    numQueue.TryDequeue(out result);
                    if (result > 0)
                    {
                        Console.WriteLine($@"[{DateTime.Now.ToString("HH:mm:ss")}]{result}");
                    }
                    else
                    {
                        Thread.Sleep(0);
                    }
                } while (true);
            });
 
 
        }
    }
}

相關文章