在Dispose()方法中是否需要调用`Clear()`?

时间:2019-06-02 23:06:53

标签: c#

以下代码创建一个ConcurrentDictionary,并在Clear()方法中调用字典的Dispose。有必要吗?

class EventAggregator : IEventAggregator
{
    public static IEventAggregator Instance { get; } = new EventAggregator();

    private readonly ConcurrentDictionary<Type, List<object>> subscriptions = new ConcurrentDictionary<Type, List<object>>();

    public void Publish<T>(T message) where T : IApplicationEvent
    {
        if (subscriptions.TryGetValue(typeof(T), out List<object> subscribers))
        {
            // To Array creates a copy in case someone unsubscribes in their own handler
            foreach (var subscriber in subscribers.ToArray())
            {
                ((Action<T>)subscriber)(message);
            }
        }
    }

    public void Subscribe<T>(Action<T> action) where T : IApplicationEvent
    {
        var subscribers = subscriptions.GetOrAdd(typeof(T), t => new List<object>());
        lock (subscribers) { subscribers.Add(action); }
    }

    public void Unsubscribe<T>(Action<T> action) where T : IApplicationEvent
    {
        //....
    }

    public void Dispose()
    {
        subscriptions.Clear(); // Is this necessary?
    }
}

0 个答案:

没有答案