I have this code, which works as I wanted but I don't understand exactly why. Thinking about a stack in C, C++, I'd guess that the p variable will be on the stack on each call, and then erased when the method returns. How does the closure of the thread captures it and more over, captures the correct value every time? The output is what I wanted - files are "_a", "_b", "_c".
public enum enumTest
{
a = 1,
b =2,
c=3
}
private void Form1_Load(object sender, EventArgs e)
{
callme(enumTest.a);
callme(enumTest.b);
callme(enumTest.c);
}
private void callme(enumTest p)
{
Thread t = new Thread(() =>
{
Thread.Sleep(2000);
Guid guid = Guid.NewGuid();
File.WriteAllText(guid.ToString() + "_" + p.ToString(), "");
});
t.Start();
}