Collection was modified; enumeration operation may not execute

If you try to add/remove items from a collection while it’s being looped over in a foreach loop (enumerated), then you’ll get the following exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.at System.Collections.Generic.List`1.Enumerator.MoveNext() This error can happen in two scenarios: The solution to this problem depends on which scenario you’re in. In this … Read more

C# – Thread-safe bool properties using Locks vs Interlocked

The following bool property is not thread-safe. Why is this thread un-safe? Let’s say you have two threads running at the same time. One thread is reading the bool property, while the other thread is changing the value from false to true. It’s possible for the reader thread to get the stale value (false instead … Read more

C# – ManualResetEventSlim and AutoResetEvent

When you want thread(s) to wait until they’re signaled before continuing, there are two simple options: I’ll show examples of using both of these. ManualResetEventSlim examples ManualResetEventSlim is like waving a flag at a car race. All race cars (threads) line up at the starting line and wait for the flag, and then they all … Read more

C# – Use SemaphoreSlim for throttling threads

When you have multiple threads trying to do work at the same time, and you want to throttle how many of them are actually executing (such as when you’re sending concurrent requests with HttpClient), you can use SemaphoreSlim. Example – a busy grocery store Grocery stores have a limited number of checkout lanes open. Let’s … Read more

Multithreaded quicksort in C#

One day I decided to challenge myself by trying to implement multithreaded quicksort. I wanted to see how it would compare to the built-in Array.Sort() method. I came up with two algorithms that were 2-4x faster than Array.Sort(): After continuing to tinker, in attempts to further optimize, I came across the AsParallel().OrderBy() method (PLINQ). After … Read more

How to update UI from another thread

I often need to be able to run multiple threads and update the UI based on the results. For example, I may need to execute GET requests to 10 different endpoints concurrently, and then report their results in a datagrid as they come back. The problem is you can’t just update the UI from any … Read more