Reputation: 38478
I am initializing a mutable class instance as a local variable with new keyword. Then I pass this object as a parameteter to a delegate. Is this variable's lifetime extended by the delegate? Do other threads use this variable or create their own instances? I may be asking the obvious but I want to be sure.
public void DoSometing(Action<Foo> action)
{
Foo foo = new Foo();
action.Invoke(foo);
}
Upvotes: 0
Views: 307
Reputation: 77556
Whenever you pass local variables that "escape" the method one way or another, you do extend its lifetime. In C# you will never operate upon a variable that contains a reference to a non-existant object -- the concept makes no sense in a managed environment.
So yes, foo
will continue to live on, and you will need to be concerned with thread-safety in exactly the same way as if you simply called another ordinary method. In this scenario, lambdas do not change the complexion of the problem.
However, sometimes this can be more subtle, especially if you return a lambda -- one which closes over local variables. In such a scenario, all the variables you reference from within the lambda live on in the same way as foo
.
Upvotes: 3