c# - Multiple anonymous event handlers - but only last one is called -
i have following code use simulate live data feed simultaneously sends message each object of type "symbol" in collection inside "portfolio.symbols" should respond (by method doing work on it).
in order true simultaneously, try register anonymous event handlers following way:
static public void registerevents() { foreach (symbol symbol in portfolio.symbols) { generatequoterequest += () => { somemethod(symbol); }; } } static public void run() { ongeneratequoterequest(); thread.sleep(100); } public delegate void ongeneratequoterequesteventhandler(); public static event ongeneratequoterequesteventhandler generatequoterequest = delegate {}; ...
i try raise event, hoping number of "somemethod" instances firing up. unfortunately, last "symbol" added called.
what missing here?
the infamous captured-variable/foreach glitch; try:
foreach (symbol symbol in portfolio.symbols) { var copy = symbol; generatequoterequest += () => { somemethod(copy); }; }
and btw; static event
s really dangerous - event subscriptions won't unsubscribe themselves, keeping lots of things in memory unnecessarily. can make them self-unsubscribing, of course:
foreach (symbol symbol in portfolio.symbols) { var copy = symbol; ongeneratequoterequesteventhandler handler = null; handler = () => { somemethod(copy); generatequoterequest -= handler; }; generatequoterequest += handler; }
Comments
Post a Comment