From the course: Advanced C#: Thread-Safe Data with Concurrent Collections

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Work with the ConcurrentBag

Work with the ConcurrentBag

- For the final example, in this chapter, let's look at the ConcurrentBag. And remember what we know, that each thread that's adding or removing items in the bag will get its own separate storage area. So, I've tried to create a demo that shows that. So, I started by creating the ConcurrentBag here I've typed robot in demo, and then the code for SetupTeam1 and SetupTeam2 is down here. And I'm calling those on two separate threads, this is similar to the other demos I've done, and then I'm waiting for those tasks to complete. And then once I've set up the bag and added items to it, I'm doing the usual here, where I try to peek and look at what's the first item in there. Now, remember about how three threads here. I'll have the main thread that's running demo. I'll have another thread that's running task one, and a third thread that's running task two. So, when I do try peek, I'll be using thread number one, the ones running…

Contents