I was reading this question, and read this response
This is actually a fantastic feature.
This lets you have a closure that
accesses something normally hidden,
say, a private class variable, and let
it manipulate it in a controlled way
as a response to something like an
event.You can simulate what you want quite
easily by creating a local copy of the
variable, and using that.
Would we need to implement Lock() in this situation?
What would that look like?
According to Eric Lippert a compiler makes code look like this:
private class Locals
{
public int count;
public void Anonymous()
{
this.count++;
}
}
public Action Counter()
{
Locals locals = new Locals();
locals.count = 0;
Action counter = new Action(locals.Anonymous);
return counter;
}
What does the Lambda would look like, as well as the long-form code?
If you have a reason to lock, then yes, there’s nothing stopping you from putting a
lockstatement in a closure.For example, you could do this:
What does this look like, in terms of compiler-generated code? Ask yourself: what is captured?
objectused for locking.IList<T>passed in.These will be captured as instance fields in a compiler-generated class. So the result will look something like this:
Does that make sense?