当前位置:Gxlcms > 数据库问题 > access to modified closure 闭包的问题

access to modified closure 闭包的问题

时间:2021-07-01 10:21:17 帮助过:3人阅读

(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

 

access to modified closure 闭包的问题

标签:

人气教程排行