Save time with parallel FOR loop

Parallel.For() can improve performance a lot by parallelizing your code, but it also has overhead (synchronization between threads, invoking the delegate on each iteration). And since in your code, each iteration is very short (basically, just a few CPU instructions), this overhead can become prominent. Because of this, I thought using Parallel.For() is not the … Read more

List thread safety

No! It is not safe at all, because processed.Add is not. You can do following: items.AsParallel().Select(item => SomeProcessingFunc(item)).ToList(); Keep in mind that Parallel.ForEach was created mostly for imperative operations for each element of sequence. What you do is map: project each value of sequence. That is what Select was created for. AsParallel scales it across … Read more

When to dispose CancellationTokenSource?

Speaking about whether it’s really necessary to call Dispose on CancellationTokenSource… I had a memory leak in my project and it turned out that CancellationTokenSource was the problem. My project has a service, that is constantly reading database and fires off different tasks, and I was passing linked cancellation tokens to my workers, so even … Read more