c# - List/Collection blocked until its filled -
i trying achieve easy describe, cannot find how.
i want blocked until list has @ least 1 element. let's have 2 workers.
collection c;
worker 1:
while(true) { var element = c.waitoneelement(); // stuff element }
worker 2:
// slow stuff c.add(element);
this done using semaphores, i'm wondering if there built-in class allows kind of stuff.
thanks
edit: alternatively, map callback "element added" event, don't think exists.
you can read such collections here http://www.albahari.com/threading/part5.aspx#_concurrent_collections
and heres code snippet page might
public class pcqueue : idisposable { blockingcollection<action> _taskq = new blockingcollection<action>(); public pcqueue (int workercount) { // create , start separate task each consumer: (int = 0; < workercount; i++) task.factory.startnew (consume); } public void dispose() { _taskq.completeadding(); } public void enqueuetask (action action) { _taskq.add (action); } void consume() { // sequence we’re enumerating block when no elements // available , end when completeadding called. foreach (action action in _taskq.getconsumingenumerable()) action(); // perform task. } }
notice consume method blocks until theres item in collection.
Comments
Post a Comment