在C#wpf中的单例类中实现事件处理程序

时间:2016-04-10 02:12:06

标签: c# wpf events callback singleton

我将WebSocket类配置为单例:

public class ViSoftAdsHub : ViewModelBase
{
    private static ViSoftAdsHub _instance;

    ViSoftAdsHub()
    {
        ConnectAsync();
    }
    public static ViSoftAdsHub Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new ViSoftAdsHub();
            }
            return _instance;
        }
    }
}

任何类型的多个对象实例都可以向此单例添加通知:

public void AddNotification(string name, ConfigurationsConfigSectionAdd sourceConfig,Type t)
{
    NotificationObject no = new NotificationObject
    {
        ConnectionSettings = sourceConfig,
        Name = name,
        type = t
    };
    _Notifications.Add(name, no);
}

我只需要在创建通知的对象的回调中触发回调。现在,当在集线器中收到通知时,它将触发所有对象的所有回调。

这是单例中的事件实现:

protected virtual void OnNotification(ViSoftNotificationEventArgs e)
{
    EventHandler<ViSoftNotificationEventArgs> handler = Notification;
    if (handler != null)
    {
        handler(this, e);
    }
}
public event EventHandler<ViSoftNotificationEventArgs> Notification;

public void OnMessage2(ViSoftNotificationEventArgs arg1, Type arg2)
{
    OnNotification(arg1 as ViSoftNotificationEventArgs);  
}

订阅该事件的对象的调用方法:

hub = ViSoftAdsHub.Instance;
hub.Notification += new EventHandler<ViSoftNotificationEventArgs>(Hub_Notification);
hub.AddNotification(Name, SourceConfig, typeof(Sometype));

我也遇到了重大内存泄漏。

0 个答案:

没有答案