开发者

List/Collection blocked until its filled

开发者 https://www.devze.com 2023-02-12 02:16 出处:网络
I am trying to achieve something easy to describe, but I cannot find how. I want to be blocked until a list has at least one element. Let\'s say we have two workers.

I am trying to achieve something easy to describe, but I cannot find how.

I want to be blocked until a list has at least one element. Let's say we have two workers.

Collection c;

Worker 1:

while(true) {
  var element = c.waitOneElement();
  // Do some stuff with element
}

Worker 2:

// Do some slow stuff
c.Add(element);

This could be done using semaphores, but I'm wondering if there is a built-in class that allows that kind of stuff.

Thanks

Edit: Alternatively, I could map a callback to a "Element added" event, but I don't think it exi开发者_运维知识库sts.


You can read about such collections here http://www.albahari.com/threading/part5.aspx#_Concurrent_Collections

and heres a code snippet from that page you might like

   public class PCQueue : IDisposable
    {
      BlockingCollection<Action> _taskQ = new BlockingCollection<Action>(); 
      public PCQueue (int workerCount)
      {
        // Create and start a separate Task for each consumer:
        for (int i = 0; i < workerCount; i++)
          Task.Factory.StartNew (Consume);
      }

      public void Dispose() { _taskQ.CompleteAdding(); }

      public void EnqueueTask (Action action) { _taskQ.Add (action); }

      void Consume()
      {
        // This sequence that we’re enumerating will block when no elements
        // are available and will end when CompleteAdding is called. 
        foreach (Action action in _taskQ.GetConsumingEnumerable())
          action();     // Perform task.
      }
    }

Notice that Consume method blocks until theres an item in collection.


With .Net 4 you got the Task Parallel Library. With that you can find the System.Collections.Concurrent Namespace. Here you'll find some collections which are capable for what you're trying to do.

Maybe you should also take a look into the document Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号