gpt4 book ai didi

c# - 可以在闭包中 Lock() 吗?这在 Lambda 和代码输出中是什么样子的?

转载 作者:行者123 更新时间:2023-11-30 14:02:59 25 4
gpt4 key购买 nike

我正在阅读 this问题,并阅读此回复

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.

在这种情况下我们需要实现 Lock() 吗?

那会是什么样子?

根据 Eric Lippert 的说法,编译器使代码看起来像 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;
}

Lambda 以及长格式代码会是什么样子?

最佳答案

如果您锁定的理由,那么是的,没有什么能阻止您放置 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);
}

这有意义吗?

关于c# - 可以在闭包中 Lock() 吗?这在 Lambda 和代码输出中是什么样子的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4778802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com