Problem with another "execution context" of anonymous method in loop

I have a problem with an anonymous method in a loop.

The following code is just to illustrate my problem:

private void Form1_Load(object sender, EventArgs e) { List<string> bassists = new List<string>(){ "Jaco Pastorius", "Marcus Miller", "Flea", "Vicor Wooten" }; foreach (string item in bassists) { this.button1.Click += (s, ea) => Output(s, ea, item); } } private void Output(object s, EventArgs e, string item) { this.listBox1.Items.Add(item); } 

And when I click the button, the output is:

Victor Wooten
Victor Wooten
Victor Wooten
Victor Wooten

instead:

Jaco Pastorius
Marcus Miller
Flea
Vicor wooten

The highlight of my problem is the context of making the differences. I know my example is stupid.

+8
c # anonymous-methods
source share
3 answers

This is the problem of captured variables. Correct it by changing

 foreach (string item in bassists) { this.button1.Click += (s, ea) => Output(s, ea, item); } 

to

 foreach (string item in bassists) { string currentItem = item; this.button1.Click += (s, ea) => Output(s, ea, currentItem); } 

Here is an explanation of the problem: The closing loop variable is considered harmful . By placing the local variable currentItem in the loop area and closing it, we now commit this variable instead of the loop variable.

+12
source share

Your problem is that you create new handlers in a loop, which is not necessary and dangerous.

You also create an anonymous method that matters in a hard-coded loop. This is worse.

0
source share

In any case, Jason's answer is correct. This is the problem of capturing variables. This will happen in two situations. Threading and Anonymous Ways

0
source share

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


All Articles