c# - Concurrent collections eating too much cpu without Thread.Sleep -


what correct usage of either, blockingcollection or concurrentqueue can freely dequeue items without burning out half or more of cpu using thread ?

i running tests using 2 threads , unless had thread.sleep of @ least 50~100ms hit @ least 50% of cpu.

here fictional example:

private void _dequeueitem() {     object o = null;     while(socket.connected)     {         while (!listofqueueitems.isempty)         {             if (listofqueueitems.trydequeue(out o))             {                 // use data             }         }     } } 

with above example have set thread.sleep cpu doesnt blow up.

note: have tried without while isempty check, result same.

it not because of blockingcollection or concurrentqueue, while loop:

while(socket.connected) {     while (!listofqueueitems.isempty)     { /*code*/ } } 

of course take cpu down; because of if queue empty, while loop like:

while (true) ; 

which in turn eat cpu resources.

this not way of using concurrentqueue should use autoresetevent whenever item added notified. example:

private concurrentqueue<data> _queue = new concurrentqueue<data>(); private autoresetevent _queuenotifier = new autoresetevent(false);  //at producer: _queue.enqueue(new data()); _queuenotifier.set();  //at consumer: while (true)//or condition {     _queuenotifier.waitone();//here block until receive signal notification.     data data;     if (_queue.trydequeue(out data))     {         //handle data     } } 

for usage of blockingcollection should use getconsumingenumerable() wait items added, like:

//declare buffer private blockingcollection<data> _buffer = new blockingcollection<data>(new concurrentqueue<data>());  //at producer method: _messagebuffer.add(new data());  //at consumer foreach (data data in _buffer.getconsumingenumerable())//it block here automatically waiting new items added , not take cpu down  {     //handle data here. } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -