时间:2021-07-01 10:21:17 帮助过:3人阅读
代码里面有一个for循环
循环内部调用了匿名委托
模拟了一下:
但是下面这段代码的执行,不会出现问题是正常的
private void button1_Click(object sender, EventArgs e) { Thread thread = new Thread(Closure); thread.IsBackground = true; thread.Start(); } private void Closure() { for (int i = 0; i < 10; i++) { this.Invoke((MethodInvoker) delegate { textBox1.AppendText(string.Format("{0}:{1}{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), i, Environment.NewLine)); }); } }
References:
http://stackoverflow.com/questions/595482/what-are-closures-in-c
A closure in C# takes the form of an in-line delegate/anonymous method.
A closure is attached to its parent method meaning that variables defined in parent‘s method body can be referenced from within the anonymous method.
http://csharpindepth.com/Articles/Chapter5/Closures.aspx
access to modified closure 闭包的问题
标签: