How do I find out if someone has signed up for an event?

I have a use case when I have to unsubscribe from an event. But before I unsubscribe, I want to make sure that this guy really connected to this event or not.

Please let me know how can I achieve this?

+3
source share
4 answers

The Publisher class example provides one Publish event. The IsRegistered method queries event-related event handlers for this instance of the class and returns true if this class instance has at least one registered / attached event handler. The overridden IsRegistered method does the same, but for static types.

Put this code in the console application project and press F5 to debug, try.

internal class Publisher
{
    internal event EventHandler<EventArgs> Publish;

    internal bool IsRegistered(Type type)
    {
        if (Publish == null) return false;
        //
        return (from item in Publish.GetInvocationList() where item.Target == null & item.Method.DeclaringType == type select item).Count() > 0;

    }
    internal bool IsRegistered(object instance)
    {
        if (Publish == null) return false;
        //
        return (from item in Publish.GetInvocationList() where item.Target == instance select item).Count() > 0;
    }

    static int Main(string[] args)
    {
        Publisher p = new Publisher();
        //
        p.Publish += new EventHandler<EventArgs>(static_Publish);
        p.Publish += new EventHandler<EventArgs>(p.instance_Publish);            
        //
        Console.WriteLine("eventhandler static_Publish attach: {0}", p.IsRegistered(typeof(Program)));
        Console.WriteLine("eventhandler instance_Publish attach: {0}", p.IsRegistered(program));
        //
        return 0;
    }

    void instance_Publish(object sender, EventArgs e)
    {

    }
    static void static_Publish(object sender, EventArgs e)
    {

    }
}`
+1
source

From Microsoft :

        // Wrap event invocations inside a protected virtual method
        // to allow derived classes to override the event invocation behavior
        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<CustomEventArgs> handler = RaiseCustomEvent;

            // Event will be null if there are no subscribers
            if (handler != null)
            {
                // Format the string to send inside the CustomEventArgs parameter
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

                // Use the () operator to raise the event.
                handler(this, e);
            }
        }

You are looking for the if (handler! = Null) part . It is null if there are no subscribers, but not null if there are subscribers.

+3
source

pub/sub, provider.Unsubscribe(EventType, ) ,

0

:

  • , , , , . , , , . , , , , .
  • , , , . , Linq, .Contains .

The first case may look like the code below. This will create a new delegate chain in the temporary variable with the delegate you want to delete, delete, and then compare the temporary chain with the existing chain. If they match, there was no delegate.

private EventHandler _Changed;
public event EventHandler Changed
{
    add
    {
        _Changed += value;
    }
    remove
    {
        EventHandler temp = _Changed - value;
        if (_Changed == null || temp == _Changed)
            throw new InvalidOperationException(
                "Delegate is not subscribed, cannot unsubscribe");
        _Changed = temp;
    }
}

The second, like the code below, will just see if the delegate you want to cancel is present in the delegate chain.

private EventHandler _Changed;
public event EventHandler Changed
{
    add
    {
        _Changed += value;
    }

    remove
    {
        if (_Changed == null || !_Changed.GetInvocationList().Contains(value))
            throw new InvalidOperationException(
                "Delegate is not subscribed, cannot unsubscribe");
        _Changed -= value;
    }
}

Please note that if you want, use the same code to handle the case when a delegate is added twice.

0
source

Source: https://habr.com/ru/post/1717314/


All Articles