for(inti =0; i < ListBoxDevices.Items.Count; i++) { varTempdeviceid =Listboxdevices.items[i]. ToString (); if(Tempdeviceid.contains ("(drop line)")) { varid = Globalconvert.getdeviceid (tempdeviceid.replace ("(drop line)",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); } }); } } }
There's a for loop inside the code.
An anonymous delegate is called Inside the loop
Simulate a bit:
But the execution of the following code does not appear to be the problem is normal
Private voidButton1_Click (Objectsender, EventArgs e) {Thread Thread=NewThread (Closure); Thread. IsBackground=true; Thread. Start (); } Private voidClosure () { for(inti =0; I <Ten; 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 this variables defined in parent's method body can be referenced from W Ithin the anonymous method.
Http://csharpindepth.com/Articles/Chapter5/Closures.aspx
Problems with access to modified closure closures