5

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()?

HPT
  • 351
  • 2
  • 11

2 Answers2

9

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
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Of course Foo2() could also assign the delegate to a variable, and another function much later (and possibly on another thread, or even the original thread) could end up executing it, potentially numerous times. Its a – cdiggins Sep 19 '11 at 01:51
0

The delegate could be called never or multiple times. Foo2() could do anything it wants with the delegate including assigning it to a variable somewhere or ignoring it altogether.

We only know that if run it must happen at some point after the thread has started and Foo1() has executed without throwing an uncaught exception.

cdiggins
  • 17,602
  • 7
  • 105
  • 102