是MemoryCache.Set()是线程安全的? [英] Is MemoryCache.Set() thread-safe?

查看:503
本文介绍了是MemoryCache.Set()是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助为MemoryCache.Set MSDN文档不幸的无论是主题不明确说明-safe与否。

The MSDN documentation for MemoryCache.Set unfortunately doesn’t state explicitly whether it is thread-safe or not.

时可以安全使用获得()。集()从没有明确的锁定多个线程?

Is it safe to use .Get() and .Set() from several threads without an explicit lock?

推荐答案

是的,MemoryCache类<一HREF =htt​​ps://connect.microsoft.com/VisualStudio/feedback/details/564840/the-memorycache-instance-returned-by-memorycache-default-should-be-thread-safe>是线程安全的:

Yes, the MemoryCache class is thread safe:

System.Runtime.Caching.MemoryCache是​​线程安全的。多个并发
线程可以读取和写入的MemoryCache实例。内部
线程安全是自动处理,以确保高速缓存以一致的方式被更新

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方法是线程安全的,但如果你可能会被存储到数据结构此缓存不是线程安全的,你可能会遇到麻烦。试想一下,比如你保存这个缓存中的字典。然后,当线程1使用获取来获取字典,并开始从中读取,线程使用获取来获取同样的字典和试图写它。而Get操作将是线程安全的未来会发生什么可能是非常讨厌的。

This being said the Get and Set methods are thread safe but if the data structure you might be storing into this cache is not thread safe you might get into trouble. Imagine for example that you stored a dictionary inside this cache. Then while thread1 uses Get to fetch the dictionary and starts reading from it, thread2 uses Get to fetch this same dictionary and tries to write to it. While the Get operation will be thread safe what will happen next could be pretty nasty.

这篇关于是MemoryCache.Set()是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆