自己的demo
for (int i = ; 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 = ; i < ; 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));
});
}
}
What are 'closures' in .NET?
I have an article on this very topic. (It has lots of examples.)
In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.
The general feature of closures is implemented in C# by anonymous methods and lambda expressions.
Here's an example using an anonymous method:
using System;
class Test
{
static void Main()
{
Action action = CreateAction();
action();
action();
}
static Action CreateAction()
{
int counter = 0;
return delegate
{
// Yes, it could be done in one statement;
// but it is clearer like this.
counter++;
Console.WriteLine("counter={0}", counter);
};
}
}
Output:
counter=1
counter=2
Here we can see that the action returned by CreateAction still has access to the counter variable, and can indeed increment it, even though CreateAction itself has finished.
References:
http://*.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