问题描述
我一直在阅读各种内容,看起来这应该可行,但我想确定一下.我有一个应该是缓存的静态属性(加上一些与缓存数据相关的其他功能).它将实际数据存储在 ConcurrentBag 中,并且它有一个 IEnumerable 方法来[过滤和]从这个包中产生返回值.它会像这样自我更新:
I've been reading various things and it seems like this should work but I want to be sure. I have a static property that is supposed to be a cache (plus some other functionality related to the cache data). It stores the actual data in a ConcurrentBag, and it has an IEnumerable method to [filter and] yield return values from this bag. It updates itself like this:
ConcurrentBag<Foo> NewBag = GetNewThings();
Cache = NewBag;
从我读到的内容来看,这似乎应该有效,尽管我没想到会这样.我预计这会炸毁发生这种情况时正在读取的任何迭代器.但是我读到,如果另一个线程遍历旧列表,它将在该列表实例上完成,而新列表被交换.第二个(新)线程将在新列表上启动,即使旧线程仍在迭代它们的旧实例.不过这看起来很神奇,所以我可能错了,是吗?
From what I've read, it seems like this should work, though I didn't expect it to. I expected this to blow up any iterators that were reading when this happens. However I read that if another thread were iterating through the old list, it would finish on that instance of the list while the new list gets swapped. A second (new) thread would start on the new list, even while the old thread is still iterating through their old instance. This seems magic though, so I'm probably wrong, yes?
其他线程只迭代列表,唯一的写入发生在这两行.
The other threads only iterate the list, the only writing happens here on these two lines.
推荐答案
你读的是正确的.
这是线程安全的,但您可能希望使变量 volatile
或使用 Volatile.Read
和 Volatile.Write
来确保所有线程的即时可见性.
This is thread-safe, but you might want to make the variable volatile
or use Volatile.Read
and Volatile.Write
to ensure immediate visibility to all threads.
这篇关于当可能存在迭代器时,替换并发集合是否是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!