In this example, I’ve made a dinner decision maker, that randomly decides what to eat for dinner for the next N days. In our program, we’ll randomly select from dinner choices, and add them to a dictionary.
Its best to use a Concurrent Dictionary as a thread safe collection to add items to during a parallel loop. Additions to the collection are performed by TryAdd(). We’ll add unique keys and values to the collection potentially at the same time. The TryAdd() method returns true if the key/value pair was added successfully, false if already exists. Keep in mind executing code in parallel is not always the right choice, and can lead to some pitfalls.
In the code below, we’re executing a code block in parallel. I’ve made the current thread sleep for a random amount of time inside the parallel block, as it seems to generate a more wide variety of dinners. The code block could have been a named function instead. The point is that the operating system will decide if and how to execute the code at run time. It may result in a not so improved performance, or it may not.