Threading and lambda expressions Threading and lambda expressions multithreading multithreading

Threading and lambda expressions


The only difference is that in scenario two you are closing over the e variable which effectively moves the stack variable e into a custom type that is moved to the heap so you don't lose it.

I think this ought to work fine.

Edit: As for performance, no there ought not to be a significant difference between the two scenarios. In scenario 1 you are already passing the exception as state to the QueueUserWorkItem method which internally moves that exception reference onto the heap. The only overhead is that when you use a closure is that the compiler creates a type for you and stores any captured variables as fields on that type.


Just to note, instead of the Lambda, you could do the same with an anonymous method, and it would also work in C# 2.0:

ThreadPool.QueueUserWorkItem(delegate(Object e)     {         Logger.Log(e as Exception);     });