Numerous anonymous event handlers, but only the last

I have the following code that I use to simulate a live data transfer, which simultaneously sends a message saying that each object of the Symbol type in the collection inside the Portfolio. Symbols should respond (in a different way, doing some work on it).

In order for this to be true at the same time, I am trying to register anonymous event handlers as follows:

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 {}; ... 

Then I try to raise this event, hoping that I will get several instances of "SomeMethod". Unfortunately, only the last character added is called.

What am I missing here?

+4
source share
1 answer

Shameful capture / variable / failure; try:

 foreach (Symbol symbol in Portfolio.Symbols) { var copy = symbol; GenerateQuoteRequest += () => { SomeMethod(copy); }; } 

and btw; static event really dangerous - these event subscriptions will not be unsubscribed by yourself, so you could store a lot of things in memory without unnecessary things. Of course you can make them self-signed:

 foreach (Symbol symbol in Portfolio.Symbols) { var copy = symbol; OnGenerateQuoteRequestEventHandler handler = null; handler = () => { SomeMethod(copy); GenerateQuoteRequest -= handler; }; GenerateQuoteRequest += handler; } 
+10
source

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


All Articles