How closure in c# works when using lambda expressions?

前端 未结 3 663
时光说笑
时光说笑 2020-12-10 14:09

In to following tutorial : http://www.albahari.com/threading/

They say that the following code :

for (int i = 0; i < 10; i++)
  new Thread (() =&         


        
3条回答
  •  清歌不尽
    2020-12-10 14:13

    As Albahari states, Although the passing arguments are value types, each thread captures the memory location thus resulting in unexpected results.

    This is happening because before the Thread had any time to start, the loop already changed whatever value that inside i.

    To avoid that, you should use a temp variable as Albahari stated, or only use it when you know the variable is not going to change.

提交回复
热议问题