✅ I don't undertand the error: capacity was less than the current size
Hey I have two versions of code and second one doesn't work
first version:
second version:
second version always throws the exception:
Unhandled exception. System.AggregateException: One or more errors occurred. (capacity was less than the current size. (Parameter 'value')) (capacity was less than the current size. (Parameter 'value')) (capacity was less than the current size. (Parameter 'value')) (capacity was less than the current size.
11 Replies
You can't just use regular list in multiple threads and appends elements to it on different threads
simple for takes 25 seconds in this case, that is why I decided to use Parallel.For
but maybe I was wrong and it shouldn't be faster
Your code is not thread safe
It's very dangerous
Look into that
hm ur right, I will change List to smth concurrent like ConcurrentBag and try to see results
forgot about thread safety
simple for was x2 faster than Parallel.For idk why
With concurrent bag and same code?
yes
Nothing unexpected tbf
I think it would work if you provide needed capacity when creating list
parallel has an overload with indices iirc, use that and an array
Yeah so when multiple threads call the Add() at the same time, it would be essentially the same as doing it without parallel, but with parallel you also get overhead of syncing threads.
So I decided to do it myself:
The second one runs almost 2x as fast as the former one.
But I've got a shitty machine, so it might be even faster on your one.
The key here is that every thread operates on their own indices, and yep it's faster
oh, thanks for this!