for (int i = 0; i < listBoxDevices.Items.Count; i++) { var tempDeviceId = listBoxDevices.Items[i].ToString(); if (tempDeviceId.Contains("(掉线)")) { var id = GlobalConvert.GetDeviceID(tempDeviceId.Replace("(掉线)", string.Empty)); if (id == reonlineId) { listBoxDevices.Invoke((MethodInvoker)delegate { try { listBoxDevices.Items[i] = GlobalConvert.GetDeviceID(reonlineId); } catch (Exception ex) { ExceptionLog.Instance.WriteLog(ex, LogType.UI); } }); } } }
代码里面有一个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
时间: 2024-10-04 19:52:01