2013-02-20 131 views
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打交道時。 我想知道如何在上面的Do While Loop中使用ConcurrentQueue的例子嗎?

一切我與TryPeek是行不通的嘗試..

任何想法?

+1

告訴我們:

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); } } 

,因爲你需要你可以旋轉起來成爲衆多消費者更多關於併發情況的信息:什麼線程正在運行您的發佈代碼?其他線程在做什麼?哪些線程寫入哪些變量? – Cameron 2013-02-20 22:27:49

+0

您使用1個生產者和1個消費者嗎? – user7116 2013-02-20 22:28:12

+0

「我用TryPeek試過的所有東西都不起作用。」它不是以什麼方式工作? – 2013-02-20 22:29:36

回答

5

您可以使用BlockingCollection<T>作爲生產者 - 消費者隊列。

我的回答讓你的架構一些假設,但你可能可以把它壓在您認爲合適:

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

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

// 2 workers 
Parallel.Invoke(process, process); 
+2

我想這是OP所需要的。他可能需要*不同的東西,但這是他需要的。 – usr 2013-02-20 22:52:18

+0

我能夠修改這個,我的結構(雖然試圖瞭解它)。我的確看到了性能的顯着提高。 – webdad3 2013-02-21 16:45:14

+0

+1。出於興趣,我相信'while(true)'可以通過'BlockingCollection'的[foreach'迭代[GetConsumingEnumerable()]簡化(http://msdn.microsoft.com/en-us/library /dd287186.aspx) – StuartLC 2013-09-22 05:12:58