Thread-safe Dictionary.Add

前端 未结 2 941
面向向阳花
面向向阳花 2021-02-07 08:52

Is Dictionary.Add() thread safe when you only insert?

I\'ve got a code that insert keys from multiple-threads, do I still need locking around Dictionary.Ad

2条回答
  •  攒了一身酷
    2021-02-07 09:10

    Yup, this is the exception you can get when you insert an element just as the dictionary is busy increasing the number of buckets. Triggered by another thread adding an item and the load factor got too high. Dictionary is especially sensitive to that because the reorganization takes a while. Good thing, makes your code crash quickly instead of only once a week.

    Review every line of code that's used in a thread and check where a shared object is used. You haven't yet found the once-a-week crashes. Or worse, the ones that don't crash but just generate bad data once in a while.

提交回复
热议问题