2012-12-10 37 views
1

我在.Net中使用了ConcurrentDictionary,並且愛上了使用它編寫併發類的容易程度。.Net中是否有類似ConcurrentSet的東西?

現在,我有一個不同的場景。我基本上需要跟蹤一個單一的對象類型在一個非重複的無序列表中,所以基本上是一個Set<T>類型的東西,除了它需要所有的線程安全性,我期望從ConcurrentDictionary,所以有GetOrAdd

有沒有像這樣的東西內置到.NET中?

我認爲只是用ConcurrentDictionary,只擔心鍵,從來沒有使用的價值,但這似乎非常次優

+1

的可能重複:http://stackoverflow.com/questions/4306936/how-to-implement-concurrenthashset-in-net – rossipedia

回答

0

沒有,但你可以通過引用FSharp創建一個線程安全的集合。 Core.dll並使用Microsoft.FSharp.Collections。

只是換行使用interlocked.CompareExhchange添加和刪除。

性能因組的大小而異。但你應該能夠處理數十萬個項目。

這會處理大量的線程讀取和寫入設置。

也把「鎖」(不是一個真正的鎖,原子操作的只是面積)大約是字裏行間的一切:

initialSet = sharedSet;

做=(initialSet == Interlocked.CompareExchange(參照sharedSet,newSet,initialSet));

FSharpSet<MyClass> _myItems; 

InterLockedSetAdd(ref _myItems, Item); 

    public static void InterLockedSetAdd<T>(ref FSharpSet<T> sharedSet, T item) 
    { 

     FSharpSet<T> initialSet; 
     FSharpSet<T> newSet; 
     var spin = new SpinWait(); 
     bool done = false; 

     while (!done) 
     { 
      initialSet = sharedSet; 
      newSet = sharedSet.Add(item); 
      done = (initialSet == Interlocked.CompareExchange(ref sharedSet, newSet, initialSet)); 
      if (!done) spin.SpinOnce(); 
     } 
    } 
+0

爲什麼使用FSharpSet?爲什麼不使用System.Collections.Generic的HashSet? –

相關問題