Monday, June 8, 2015

Start new thread using lambda expression and anonymous method

Old way
Thread thread = new Thread(doStuff);
thread.Start();

void doStuff()
{
    //do lots of stuff
}

Using lambda expression
Task.Factory.StartNew(() => doStuff());

void doStuff()
{
    //do lots of stuff
}

That's a little easier, but I still have to make a separate method (doStuff) just to do stuff in another thread.

Anonymous method
Task.Factory.StartNew(() =>
          { //cut and paste doStuff()'s body in here
               //do lots of stuff
          }

);

Sweet, now I don't need to add a new method just to do stuff in a new thread.

No comments:

Post a Comment

There was an error in this gadget