29

如果队列中没有项目,ConcurrentQueue 中的 TryDequeue 将返回 false。

如果队列为空,我需要我的队列将等到将新项目添加到队列中并将新项目出列,并且该过程将继续这样。

我应该在 C# 4.0 中使用 monitor.enter、wait、pulse 还是任何更好的选项

4

3 回答 3

51

这不是BlockingCollection的设计目的吗?

据我了解,您可以使用其中之一包装您的 ConcurrentQueue ,然后调用Take

于 2011-02-16T08:45:25.727 回答
2

您可以使用BlockingCollection

做这样的事情:

private BlockingCollection<string> rowsQueue;
private void ProcessFiles() {
   this.rowsQueue = new BlockingCollection<string>(new ConcurrentBag<string>(), 1000);
   ReadFiles(new List<string>() { "file1.txt", "file2.txt" });


   while (!this.rowsQueue.IsCompleted || this.rowsQueue.Count > 0)
   {
       string line = this.rowsQueue.Take();

       // Do something
   }
}

private Task ReadFiles(List<string> fileNames)
{
    Task task = new Task(() =>
    {
        Parallel.ForEach(
        fileNames,
        new ParallelOptions
        {
            MaxDegreeOfParallelism = 10
        },
            (fileName) =>
            {
                using (StreamReader sr = File.OpenText(fileName))
                {
                    string line = String.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                           this.rowsQueue.Add(line);
                    }
                }
            });

        this.rowsQueue.CompleteAdding();
    });

    task.Start();

    return task;
}
于 2018-08-14T22:51:15.340 回答
-1

您可以定期检查队列中的元素数量,当元素数量大于零时,您可以使用例如 ManualResetEvent 向线程发出信号,该线程将元素从队列中取出,直到队列为空。

这是此的伪代码:

检查线程:

while(true)
{
  int QueueLength = 0;
  lock(Queue)
  {
    queueLength = Queue.Length;
  }

  if (Queue.Length > 0)
  {
    manualResetEvent.Set();
  }
  else
  {
    Thread.Sleep(...);
  }       
}    

出队线程:

while(true)
{
  if(manualResetEvent.WaitOne(timeout))
  {
    DequeueUntilQueueEmpty();
  }
}

也可以考虑在 DequeueUntilQueueEmpty 中使用锁。

于 2011-02-16T08:41:24.330 回答