In C# 2.0+, is it necessary to lock around a closure that another thread will execute? Specifically, in the example below, is the locking necessary to ensure that the Maint thread flushes its value of x to shared memory and that thread t reads its value of x from shared memory?
I think it is, but if I'm wrong, please reference e.g. an authoritative (e.g., MSDN) article indicating why not. Thanks!
delegate void Foo();
public static void Main()
{
Foo foo = null;
object guard = new object();
int x = 1;
lock (guard)
{
foo = () =>
{
int temp;
lock (guard) temp = x;
Console.WriteLine(temp);
};
}
Thread t = new Thread(() => foo());
t.Start();
t.Join();
}
Edit: Clarified that I want to know for C# 2.0+, which is to say that the .NET 2.0+'s stronger memory model (than ECMA 335 CLI) is in effect.