Saturday, May 15, 2010

Eliminating delegates in threading

Just a quick note on threading. One way to start a new thread with parameters was the following:

Thread processingThread = new Thread(new ThreadStart(delegate { someClass.SomeMethod(); }));

processingThread.Start();


One can do the same thing with a lambda expression which in my opinion is a bit cleaner. Why? I don't know - personal preference - I seem to remember lambda syntax more often : )

Thread workerThread = new Thread(
()=> someClass.SomeMethod()(employeeId)
);
workerThread.Start();

Or doing this inline with the start right away:

(new Thread(() =>
{
someClass.SomeMethod()(employeeId)

}
)).Start();



That's all there is to it. Remember in Win32 API when creating threads, and security descriptors, etc? Its so nice and easy in the managed world.

1 comment:

Note: Only a member of this blog may post a comment.