Is this solution thread safe? Technically, yes, actually no.
The most understandable thread-safe List
(as opposed to a queue or bag) is that the list is safe with respect to order or, more strictly, index, since there is no key except an ascending integer. In a parallel world, this is a kind of meaningless concept when you think about it. This is why the System.Collections.Concurrent namespace contains a ConcurrentBag
and a ConcurrentQueue
, but not a ConcurrentList
.
Since you are asking about thread safety in a list, I assume that your software should generate a list that is in ascending order. If so, no, your solution will not work. Although the code is technically thread safe, threads can end in any order and your result
variable stops sorting.
If you want to use parallel computing, you must save your results in a bag, and then, when all the threads have finished, sort the package to create an ordered list. Otherwise, you must perform the calculation sequentially.
And since you should still use the bag, you can use the ConcurrentBag , and then you donβt have to worry about lock{}
.
source share