如何处理字典中的一次性资源

Ank*_*kar 3 c# dictionary idisposable

我们有一些处理一次性资源操作的数据源类,如下所示:

public class SomeDataStore
{
    private readonly object dictionaryLock = new object();

    private readonly Dictionary<uint, SomeDisposableClass> dataStore = new Dictionary<uint, SomeDisposableClass>();

    public bool Remove(uint key)
    {
        bool returnValue = false;

        lock (dictionaryLock)
        {
            returnValue = dataStore.Remove(key);
        }

        //OR...

        lock (dictionaryLock)
        {
            SomeDisposableClass element;

            if (dataStore.TryGetValue(key, out element))
            {
                element.Dispose();
                returnValue = dataStore.Remove(key);
            }
        }

        return returnValue;
    }

    public void Clear()
    {
        lock (dictionaryLock)
        {
            dataStore.Clear();
        }

        //OR...

        lock (dictionaryLock)
        {
            foreach (var value in dataStore.Values)
                value.Dispose();

            dataStore.Clear();
        }
    }

    //Some other Datastore access members
}

public class SomeDisposableClass : IDisposable
{
    public void Dispose()
    {
        //Dispose resources..
    }
}
Run Code Online (Sandbox Code Playgroud)

不确定哪个版本应该更好,为什么?Dictionary或是否ClearRemove内部处理disposable资源?

Him*_*ere 5

为什么字典中的元素在从字典中删除后会被自动处理?它可能存在于另一个列表或其他列表中。话虽如此,在某些集合中删除对象时处置它是非常危险的。您提到的方法(Remove,,Clear等等)都没有关于一次性物品的任何知识。所有这些方法所做的就是从内部缓存中删除对实例的引用。然而,删除对对象的引用并不意味着它应该被释放(GC)甚至处置(IDisposable)。这实际上与一次性物品无关。例如,如果另一个列表中存在对对象的另一个引用,则即使 GC 也不会释放您的对象。

\n\n

因此,您应该始终将资源放置在您可以控制的地方 - 通常与您创建资源的环境相同。

\n