相关疑难解决方法(0)

实现线程安全字典的最佳方法是什么?

我能够通过从IDictionary派生并定义一个私有的SyncRoot对象,在C#中实现一个线程安全的Dictionary:

public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
    private readonly object syncRoot = new object();
    private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();

    public object SyncRoot
    {
        get { return syncRoot; }
    } 

    public void Add(TKey key, TValue value)
    {
        lock (syncRoot)
        {
            d.Add(key, value);
        }
    }

    // more IDictionary members...
}
Run Code Online (Sandbox Code Playgroud)

然后,我在整个消费者(多个线程)中锁定此SyncRoot对象:

例:

lock (m_MySharedDictionary.SyncRoot)
{
    m_MySharedDictionary.Add(...);
}
Run Code Online (Sandbox Code Playgroud)

我能够使它工作,但这导致了一些丑陋的代码.我的问题是,是否有更好,更优雅的方式来实现线程安全的字典?

.net c# collections thread-safety

108
推荐指数
5
解决办法
7万
查看次数

IEnumerable <T>提供了两个GetEnumerator方法 - 它们之间有什么区别?

当我实现IEnumerable<T>界面时,我看到两个GetEnumerator方法:一个返回IEnumerator和另一个IEnumerator<T>.我何时会使用其中一种?

ienumerable ienumerator

9
推荐指数
3
解决办法
5347
查看次数

如何在我的实现IEnumerable <Foo>的Dictionary包装器类中实现IEnumerable?

我正在尝试为a创建一个包装器Dictionary<String,Foo>.

Dictionary<String,Foo>实现IEnumerable<KeyValuePair<String,Foo>>,但我希望我的包装类实现IEnumerable<Foo>.所以我尝试了这个:

public class FooCollection : IEnumerable<Foo>
{
    private Dictionary<string, Foo> fooDictionary = new Dictionary<string, Foo>();

    public IEnumerator<Foo> GetEnumerator()
    {
        return fooDictionary.Values.GetEnumerator();
    }

    // Other wrapper methods omitted

}
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误:

'FooCollection'没有实现接口成员'System.Collections.IEnumerable.GetEnumerator()'.'FooCollection.GetEnumerator()'无法实现'System.Collections.IEnumerable.GetEnumerator()',因为它没有匹配的返回类型'System.Collections.IEnumerator'.

但是我不明白这个错误,因为FooCollection.GetEnumerator()返回一个IEnumerator<Foo>,而且IEnumerator<Foo>是一个IEnumerator.

编辑:

明确实施IEnumerator.GetEnumerator()工作的解决方案.但是我现在想知道为什么当我"去定义"时,List<T>我只看到一个GetEnumerator的定义: public List<T>.Enumerator GetEnumerator();

显然,List<T>可以有一个GetEnumerator返回的东西,同时实现方法IEnumerator<T>和IEnumerator,但我必须为每一个方法?

编辑:

正如下面LukeH所回答的那样,List<T> 确实包含了显式接口实现.显然,Visual Studio在从元数据生成方法存根时不会列出那些.(请参阅前一个问题:为什么VS Metadata视图不显示显式接口实现的成员)

在发布此问题之前,我曾尝试检查List<T>(通过Visual Studio中的"转到定义")以查看是否需要实现多个版本的GetEnumerator.我想这不是最可靠的检查方式.

无论如何,我将此标记为已回答.谢谢你的帮助.

c# ienumerable

7
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

ienumerable ×2

.net ×1

collections ×1

ienumerator ×1

thread-safety ×1