// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Avalonia.Utilities
{
///
/// Manages subscriptions to events using weak listeners.
///
public static class WeakEventHandlerManager
{
///
/// Subscribes to an event on an object using a weak subscription.
///
/// The type of the target.
/// The type of the event arguments.
/// The type of the subscriber.
/// The event source.
/// The name of the event.
/// The subscriber.
public static void Subscribe(TTarget target, string eventName, EventHandler subscriber)
where TEventArgs : EventArgs where TSubscriber : class
{
var dic = SubscriptionTypeStorage.Subscribers.GetOrCreateValue(target);
Subscription sub;
if (!dic.TryGetValue(eventName, out sub))
{
dic[eventName] = sub = new Subscription(dic, typeof(TTarget), target, eventName);
}
sub.Add(subscriber);
}
///
/// Unsubscribes from an event.
///
/// The type of the event arguments.
/// The type of the subscriber.
/// The event source.
/// The name of the event.
/// The subscriber.
public static void Unsubscribe(object target, string eventName, EventHandler subscriber)
where TEventArgs : EventArgs where TSubscriber : class
{
SubscriptionDic dic;
if (SubscriptionTypeStorage.Subscribers.TryGetValue(target, out dic))
{
Subscription sub;
if (dic.TryGetValue(eventName, out sub))
{
sub.Remove(subscriber);
}
}
}
private static class SubscriptionTypeStorage
where TArgs : EventArgs where TSubscriber : class
{
public static readonly ConditionalWeakTable