c# - Single-shot event subscription -
i'm convinced isn't possible, i'm going ask nonetheless.
in order make single-shot subscription events, find myself using (self-invented) pattern:
eventhandler handler=null; handler = (sender, e) => { someevent -= handler; initialize(); }; someevent += handler; it's quite lot of boiler-plate, , makes resharper whinge modified closures. there way of turning pattern extension method or similar? better way of doing it?
ideally, i'd like:
someevent.oneshot(handler)
it's not easy refactor extension method, because way can refer event in c# subscribing (+=) or unsubscribing (-=) (unless it's declared in current class).
you use same approach in reactive extensions: observable.fromevent takes 2 delegates subscribe event unsubscribe it. that:
public static class eventhelper { public static void subscribeoneshot( action<eventhandler> subscribe, action<eventhandler> unsubscribe, eventhandler handler) { eventhandler actualhandler = null; actualhandler = (sender, e) => { unsubscribe(actualhandler); handler(sender, e); }; subscribe(actualhandler); } } ... foo f = new foo(); eventhelper.subscribeoneshot( handler => f.bar += handler, handler => f.bar -= handler, (sender, e) => { /* whatever */ });
Comments
Post a Comment