码迷,mamicode.com
首页 > 数据库 > 详细

access to modified closure 闭包的问题

时间:2015-09-15 18:18:00      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

 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

closure in C# takes the form of an in-line delegate/anonymous method.

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 闭包的问题

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4810784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!