C# 多线程以及如何确保所有内容完全同步

C# 多线程以及如何确保所有内容完全同步,c#,multithreading,queue,C#,Multithreading,Queue,首先,我的所有示例代码: class Program { static List<string> queue = new List<string>(); static System.Threading.Thread queueWorkerThread; static void Main(string[] args) { // Randomly call 'AddItemToQueue' at certain circums

首先,我的所有示例代码:

class Program
{
    static List<string> queue = new List<string>();
    static System.Threading.Thread queueWorkerThread;

    static void Main(string[] args)
    {
        // Randomly call 'AddItemToQueue' at certain circumstances and user inputs (unpredictable)
    }

    static void AddItemToQueue(string item)
    {
        queue.Add(item);

        // Check if the queue worker thread is active
        if (queueWorkerThread == null || queueWorkerThread.IsAlive == false)
        {
            queueWorkerThread = new System.Threading.Thread(QueueWorker);
            queueWorkerThread.Start();

            Console.WriteLine("Added item to queue and started queue worker!");
        }
        else
        {
            Console.WriteLine("Added item to queue and queue worker is already active!");
        }
    }

    static void QueueWorker()
    {
        do
        {
            string currentItem = queue[0];

            // ...
            // Do things with 'currentItem'
            // ...

            // Remove item from queue and process next one
            queue.RemoveAt(0);

        } while (queue.Count > 0);

        // Reference Point (in my question) <----

    }
}
类程序
{
静态列表队列=新列表();
静态System.Threading.Thread queueWorkerThread;
静态void Main(字符串[]参数)
{
//在特定情况和用户输入下随机调用“AddItemToQueue”(不可预测)
}
静态void AddItemToQueue(字符串项)
{
添加(项目);
//检查队列工作线程是否处于活动状态
if(queueWorkerThread==null | | queueWorkerThread.IsAlive==false)
{
queueWorkerThread=new System.Threading.Thread(QueueWorker);
queueWorkerThread.Start();
WriteLine(“将项目添加到队列并启动队列工作程序!”);
}
其他的
{
WriteLine(“添加到队列的项目和队列工作程序已处于活动状态!”);
}
}
静态void QueueWorker()
{
做
{
字符串currentItem=队列[0];
// ...
//使用“currentItem”进行操作
// ...
//从队列中删除项目并处理下一个项目
queue.RemoveAt(0);
}而(queue.Count>0);

//参考点(在我的问题中)请将您的代码示例放在问题本身中。什么不使用BlockingCollection?好的,将代码从屏幕截图移动到问题。只需使用
BlockingCollection
并使用多个线程作为生产者/消费者。我刚刚尝试使用BlockingCollection,到目前为止效果似乎很好!我不知道排队有那么容易在C#…无论如何,非常感谢您的帮助!请将您的代码示例放在问题本身中。什么不使用BlockingCollection?好的,将代码从屏幕截图移动到问题。只需使用
BlockingCollection
并使用多个线程作为生产者/消费者。我刚刚尝试使用BlockingCollection,到目前为止似乎效果很好!我做到了我不知道在C#排队有那么容易……无论如何,谢谢你的帮助!