本文介绍了并发SortedList或O(log n)并发集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从ASP.NET MVC应用程序中的数据库缓存大量数据,并且想使用SortedList.我知道.NET 4.0添加了并发集合,但是没有排序的集合.我当时在考虑使用SynchronizedCollection,但是它甚至在读取时都使用锁(如果我没记错的话),所以我在寻找其他选项.基本上,我需要一个访问复杂度为O(log n)的并发集合.

I need to cache a lot of data from database in ASP.NET MVC application and would like to use SortedList. I know .NET 4.0 added concurrent collections but there is no sorted collection.I was thinking to use SynchronizedCollection, but it is intensively using locks even for reads (if I am not mistaken), so I am looking for other options. Basically I need a concurrent collection with O(log n) access complexity.

编辑-基于格雷格的答案的代码

void WrappedAdd(TKey k, TValue v)
{
  var copy = new SortedList<TKey, TValue>(_sortedList);
  copy.Add(k, v);
  _sortedList = copy;
}

推荐答案

您的要求非常模糊,所以我真的不知道您想要什么.集合应该具有索引吗?键值语义?

Your requirements are pretty vague, so I don't really know what you want. Is the collection supposed to have indexing? Key-value semantics?

我不确定这是否符合您的要求,但是您可以使用新的Microsoft 不可变的收藏库.目前可以在NuGet上将其作为预览.其中包含排序后的集合(排序后的集合和词典).

I'm not sure if this fits with what you want, but you could use the new Microsoft immutable collections library. It's currently available on NuGet as a preview. It contains sorted collections (sorted sets and dictionaries), among other things.

这些集合本身不是并发的(实际上,并发不是问题;它们不能被修改).但是,您可以通过包装它们并在写入过程中使用锁来在并发设置中使用它们.读取是线程安全的,因为唯一的变化是分配了一个引用,这是一个原子操作,因此可以确保获得尽可能多的最新结果.

These collections aren't concurrent themselves (in fact, concurrency is a non-issue; they can't be modified). However, you can use them in a concurrent setting by wrapping them, and using a lock during a write. Reading is thread-safe because the only mutation is assigning a reference, which is an atomic operation, so you're guaranteed to get the most up to date results you possibly could.

它们是基于树的,因此大多数操作都是 log n .

They're tree-based so most operations are log n.

public class ConcurrentWrapper<TKey, T> {
    ImmutableSortedDictionary<TKey, T> _inner;

    public void Add(TKey key, T item) {
        lock (_inner) {
            _inner = _inner.Add(key, item);
        }
    }

    public T Get(TKey key) {
        return _inner[key];
    }
}

这篇关于并发SortedList或O(log n)并发集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:57