Search code examples
c#eventstimerevent-handling

Event triggering after subscription


I have a class that contains a queue and a form that contains a listbox.

When the user opens the form it gets all of the accumulated objects from the queue and shows them in the listbox. While the form is open as soon as the queue gets a new item it notifies the form of the new item via a custom event.

After closing the form the data will accumulate again.

My problem is the following: As soon the form is subscribed to the notification event it should dump all of the queue to the form and keep dumping it as long as someone is subscribed to the event. It should not wait until another item is added to the queue.

One solution would be to use a timer to check if there are any subscriptions to the event and then dump it. It is not much but i would be wasting resources with the timer.

It would seem to be better if the form's subscription to the event could itself trigger the event. The app is very modular and modules communicate through events to a eventNexus and then the nexus notifies everyone who needs to know.

Since an event is an object as well, it should be possible to accomplish something like this but I did not manage to find any links.


Solution

  • You can customize the adding and removing of event handlers in the code of the event itself by using the add and remove statements:

    private EventHandler onMyEvent;
    public event MyEventHandler MyEvent
    {
        add
        {
            // run when event handler is added ( += )
            onMyEvent = (MyEventHandler)Delegate.Combine(onMyEvent, value);
    
            // Add additional, custom logic here...
        }
    
        remove
        {
            // run when event handler is removed ( -= )
            onMyEvent = (MyEventHandler)Delegate.Remove(onMyEvent, value);
        }
    }
    

    Here you can add your own code to trigger actions upon adding or removing your event handler.