如果您有理由锁定,那么是的,没有什么能阻止您将lock
语句放入闭包中。
例如,您可以这样做:
public static Action<T> GetLockedAdd<T>(IList<T> list)
{
var lockObj = new object();
return x =>
{
lock (lockObj)
{
list.Add(x);
}
}
}
就编译器生成的代码而言,这是什么样的?问问自己:捕获了什么?
object
用于锁定的本地。
IList<T>
传入的。
这些将被捕获为编译器生成的类中的实例字段。所以结果看起来像这样:
class LockedAdder<T>
{
// This field serves the role of the lockObj variable; it will be
// initialized when the type is instantiated.
public object LockObj = new object();
// This field serves as the list parameter; it will be set within
// the method.
public IList<T> List;
// This is the method for the lambda.
public void Add(T x)
{
lock (LockObj)
{
List.Add(x);
}
}
}
public static Action<T> GetLockedAdd<T>(IList<T> list)
{
// Initializing the lockObj variable becomes equivalent to
// instantiating the generated class.
var lockedAdder = new LockedAdder<T> { List = list };
// The lambda becomes a method call on the instance we have
// just made.
return new Action<T>(lockedAdder.Add);
}
那有意义吗?