2

我在 C# (4.0) 中有一个常规的队列对象,并且我正在使用访问此队列的 BackgroundWorkers。

我使用的代码如下:

   do
    {
        while (dataQueue.Peek() == null // nothing waiting yet 
            && isBeingLoaded == true // and worker 1 still actively adding stuff
        )
            System.Threading.Thread.Sleep(100);

        // otherwise ready to do something: 
        if (dataQueue.Peek() != null) // because maybe the queue is complete and also empty 
        {
            string companyId = dataQueue.Dequeue();
            processLists(companyId);
            // use up the stuff here //
        } // otherwise nothing was there yet, it will resolve on the next loop.
    } while (isBeingLoaded == true // still have stuff coming at us 
           || dataQueue.Peek() != null);   // still have stuff we haven’t done

但是,我想在处理线程时我应该使用ConcurrentQueue. ConcurrentQueue我想知道是否有像上面那样在 Do While 循环 中使用 a 的示例?

我用 TryPeek 尝试的一切都不起作用..

有任何想法吗?

4

1 回答 1

5

您可以将 aBlockingCollection<T>用作生产者-消费者队列。

我的回答对您的架构做出了一些假设,但您可以根据自己的需要对其进行塑造:

public void Producer(BlockingCollection<string> ids)
{
    // assuming this.CompanyRepository exists
    foreach (var id in this.CompanyRepository.GetIds())
    {
        ids.Add(id);
    }

    ids.CompleteAdding(); // nothing left for our workers
}

public void Consumer(BlockingCollection<string> ids)
{
    while (true)
    {
       string id = null;
       try
       {
           id = ids.Take();
       } catch (InvalidOperationException) {
       }

       if (id == null) break;

       processLists(id);
    }
}

您可以根据需要启动尽可能多的消费者:

var companyIds = new BlockingCollection<string>();
Producer(companyIds);

Action process = () => Consumer(companyIds);

// 2 workers
Parallel.Invoke(process, process);
于 2013-02-20T22:34:26.713 回答