2011-12-31 9 views
3

私は、順番に処理する必要がある作業項目のリストを持っています。リストが空の場合もあれば、数千のアイテムがあることもあります。一度に1つだけ処理でき、順番に処理できます。現時点では、消費者のタスクで、Listが空であるかどうかをチェックする前に100ms待つために、私は馬鹿に見える次のことをしています。これを行う標準的な方法ですか、私は完全に間違っていますか?プロデューサ - キューが空のときにコンシューマが待機していますか?

public class WorkItem 
{ 

} 

public class WorkerClass 
{ 
    CancellationTokenSource cts = new CancellationTokenSource(); 
    CancellationToken ct = new CancellationToken(); 

    List<WorkItem> listOfWorkItems = new List<WorkItem>(); 

    public void start() 
    { 
     Task producerTask = new Task(() => producerMethod(ct), ct); 
     Task consumerTask = new Task(() => consumerMethod(ct), ct); 

     producerTask.Start(); 
     consumerTask.Start(); 
    } 

    public void producerMethod(CancellationToken _ct) 
    { 

     while (!_ct.IsCancellationRequested) 
     { 
      //Sleep random amount of time 
      Random r = new Random(); 
      Thread.Sleep(r.Next(100, 1000)); 

      WorkItem w = new WorkItem(); 
      listOfWorkItems.Add(w); 
     } 
    } 

    public void consumerMethod(CancellationToken _ct) 
    { 

     while (!_ct.IsCancellationRequested) 
     { 
      if (listOfWorkItems.Count == 0) 
      { 
       //Sleep small small amount of time to avoid continuously polling this if statement 
       Thread.Sleep(100); 
       continue; 
      } 

      //Process first item 
      doWorkOnWorkItem(listOfWorkItems[0]); 

      //Remove from list 
      listOfWorkItems.RemoveAt(0); 
     } 
    } 

    public void doWorkOnWorkItem(WorkItem w) 
    { 
     // Do work here - synchronous to execute in order (10ms to 5min execution time) 
    } 

} 

アドバイスありがとうございます。

おかげ

答えて

関連する問題