2011-12-31 3 views
3

주문을 처리해야하는 작업 항목 목록이 있습니다. 때로는 목록이 비어 있고, 때로는 1000 개의 항목이 있습니다. 한 번에 하나만 처리 할 수 ​​있습니다. 현재 나는 다음과 같은 일을하고있다. 왜냐하면 소비자 작업에서 Thread.Sleep을 사용하여 목록이 비어 있는지 확인하기 전에 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) 
    } 

} 

크게 감사드립니다.

감사

답변

관련 문제