C# – MemoryCache.Set()线程安全吗?

MSDN documentation for MemoryCache.Set不幸地没有明确指出它是否是线程安全的。

几个线程没有明确的锁定使用.Get()和.Set()是否安全?

最佳答案
是的,MemoryCache类is thread safe

System.Runtime.Caching.MemoryCache is threadsafe. Multiple concurrent
threads can read and write a MemoryCache instance. Internally
thread-safety is automatically handled to ensure the cache is updated
in a consistent manner.

What this might be referring to is that data stored within the cache
may itself not be threadsafe. For example if a List is placed in
the cache, and two separate threads both get a reference to the cached
List, the two threads will end up stepping on each other if they
both attempt to update the list simultaneously.

这被称为Get和Set方法是线程安全的,但如果您可能存储在此缓存中的数据结构不是线程安全的,您可能会遇到麻烦。想象一下,例如,您在此缓存中存储了一个字典。然后当thread1使用Get获取字典并开始读取它时,thread2使用Get获取同一个字典并尝试写入它。虽然Get操作将是线程安全的,接下来会发生什么会是非常讨厌的。

转载注明原文:C# – MemoryCache.Set()线程安全吗? - 代码日志