首页 > 数据库技术 > 详细

access to modified closure 闭包的问题

时间:2015-09-15 18:16:13      阅读:136      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!