Locking on an interned string?

前端 未结 6 1245
栀梦
栀梦 2021-01-01 16:43

Update: It is acceptable if this method is not thread safe, but I\'m interested in learning how I would make it thread safe. Also, I do not want to lock on

6条回答
  •  走了就别回头了
    2021-01-01 17:36

    According to the documentation, the Cache type is thread safe. So the downside for not synchronizing yourself is that when the item is being created, it may be created a few times before the other threads realize they don't need to create it.

    If the situation is simply to cache common static / read-only things, then don't bother synchronizing just to save the odd few collisions that might occur. (Assuming the collisions are benign.)

    The locking object won't be specific to the strings, it will be specific to the granularity of the lock you require. In this case, you are trying to lock access to the cache, so one object would service locking the cache. The idea of locking on the specific key that comes in isn't the concept locking is usually concerned with.

    If you want to stop expensive calls from occurring multiple times, then you can rip the loading logic out into a new class LoadMillionsOfRecords, call .Load and lock once on an internal locking object as per Oded's answer.

提交回复
热议问题