Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an event listener be limited to only having one subscriber?

Is it possible to stop multiple subscribers from subscribing to an event?

I have created a quick example snippet to give my question some context but unfortunately I can't test it right now because I'm not at my VS machine.

The goal is to:

  • Return an empty list if there are no subscribers.
  • Return the return value of a single subscriber.
  • Throw an exception if more than one subscriber tries to subscribe to the event (this is the crux of the matter).

Is this possible?

public delegate List<IBaseWindow> GetWindowListDelegate();
public static event GetWindowListDelegate GetWindowListEvent;

public List<IBaseWindow> GetWindowList() {

    if (GetWindowListEvent == null) {
        return new List<IBaseWindow>();
    }

    return GetWindowListEvent();
 }

Note: I'm using .NET 3.5 sp1.

like image 251
InvertedAcceleration Avatar asked Jan 16 '10 16:01

InvertedAcceleration


1 Answers

You could use event accessors to accomplish this. Something like the following:

  private EventHandler _h;
  public event EventHandler H {
      add {
         if (...) { // Your conditions here.
                    // Warning (as per comments): clients may not
                    // expect problems to occur when adding listeners!
           _h += value;
         }
      }
      remove {
         _h -= value;
      }
  }

As Andrew points out, you don't really need events to accomplish this. Is there some particular reason you need them?

like image 159
John Feminella Avatar answered Nov 15 '22 17:11

John Feminella