Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda inside Lambda

assume we have a lambda expression like

        var thread= new Thread(() =>
        {
            Foo1();
            Foo2(() =>
            {
                Foo3();
                DoSomething();
            }
            );
        });

the question is when DoSomething() evaluated? on thread creation or on calling thread.Start()?

like image 823
HPT Avatar asked Feb 23 '23 00:02

HPT


1 Answers

DoSomething() may never be called. It will only be called if Foo2() executes the delegate it's given. So the order of execution is:

  1. Delegate is created and passed to the Thread constructor. None of the code in the delegate is executed.
  2. Presumably someone calls thread.Start().
  3. Foo1() executes
  4. A delegate is created (or possibly retrieved from a cached field) representing the calls to Foo3() and DoSomething(), but those calls are not executed yet
  5. The delegate reference is passed to Foo2()
  6. If Foo2() executes the delegate, then Foo3() and DoSomething() will be executed
like image 124
Jon Skeet Avatar answered Mar 06 '23 20:03

Jon Skeet