Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two BackgroundWorkers, One List<T>

I need to have these 2 threads working constantly on a Generic List, one thread should Add items to the list, the other should "consume" the items (just look at them, do what needs to be done depeding on some of the item's properties, and then remove it).

NOTE: I'm a begginner, so any insight on how to do this is appreciated.

I'm thinking 2 BackgroundWorkers with a while(1) loop (accepting cancellations of course), with the List object passed as Argument to both.

Is this possible/safe? What should I do to make it safe?

(If you need more information, please specify what in the comments, and I'll edit this)

Thanks!

like image 788
Arturo Gurrola Avatar asked May 02 '26 03:05

Arturo Gurrola


1 Answers

Not safe. You will need locking around both reading and writing. This is the classic producer/consumer problem.

http://blogs.msdn.com/b/csharpfaq/archive/2010/08/12/blocking-collection-and-the-producer-consumer-problem.aspx

If you're using .NET 4, you can use the BlockingCollection effectively here.

like image 82
Joe Avatar answered May 03 '26 17:05

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!