c# - Is this a safe use of Dictionary in a multi-threaded method? -
i have collection of items (sortedpoints) iterate on using parallel.foreach. each item become key in dictionary named stripes. computing value each item expensive , in method bulidstripes.
parallel.foreach(sortedpoints, point => stripes[point] = buildstripes(point, pointtoposition) ); i can make stripes concurrentdictionary, wondering if work:
1) make stripes regular dictionary.
2) iterate on points serially , fill stripes mappings empty object.
3) iterate on points in parallel , replace mapping in stripes actual value returned buildstripes.
foreach(var point in sortedpoints) stripes[point] = emptystripe; parallel.foreach(sortedpoints, point => stripes[point] = buildstripes(point, pointtoposition) ); is setting value key thread-safe if each thread works on separate set of keys , each key pre-loaded dictionary serially outlined? looked @ source code dictionary , looks safe, these collections subtle beasts , parallel bugs hard spot.
once dictionary created, never modify again , accesses reads.
lets see facts. thread error can happen if:
- add new item ? nope
- resize dictionnary while adding item. not problem, dictionary has fixed size.
- two threads try set value of same key. won't happen because sortedpoints collection have distinct item (does it?)
is there other option? don't see one. think safe go method.
but use regular concurrentdictionnary readibility of course! perhaps can gain performance, unless benchmark it, there no reason not use concurrentdictionary.
Comments
Post a Comment