假设我们有一个类似
的 lambda 表达式 var thread= new Thread(() =>
{
Foo1();
Foo2(() =>
{
Foo3();
DoSomething();
}
);
});
问题是 DoSomething()
何时求值?在 thread
创建或调用 thread.Start()
时?
最佳答案
DoSomething()
可能永远不会 被调用。它只会在 Foo2()
执行给它的委托(delegate)时被调用。所以执行顺序是:
- Delegate 被创建并传递给
Thread
构造函数。委托(delegate)中的代码均未执行。 - 可能有人调用了
thread.Start()
。 Foo1()
执行- 创建(或可能从缓存字段中检索)代表对
Foo3()
和DoSomething()
的调用,但这些调用尚未执行 - 委托(delegate)引用传递给
Foo2()
- 如果
Foo2()
执行委托(delegate),thenFoo3()
和DoSomething()
将被执行
关于c# - Lambda 内部的 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7376977/