Tutorial :Are lambda expressions multi-threaded?


Are lambda expressions multi-threaded?

Say when you write a mathematical formula as a lambda method, when you pass it to another method, would it be multi-threaded?


Not 100% clear on what you're asking.

Are you asking if lambdas are naturally run on a different thread?

If so no, they are just another instance of System.Delegate and run on the main thread unless specifically asked to do otherwise.

Are you asking if they are safe to run on multiple threads?

This is a question that can only be answered by knowing the contents of the lambda expression. They are not inherently thread safe. In my experience the are much less likely to be thread safe than you would expect.


No, they are executed on the thread they are created on unless you pass it to another thread, just like any other method. You would not want them to run on a different thread automatically, trust me.


In the next version of C#, they are adding multi-threading options to LINQ (called PLINQ) and delegates. Check out more info here. Currently, it's all on a single thread.


As others have said, lambda expressions are not inherently multi-threaded, nor do the standard linq-to-objects extension methods do anything special to call them in separate threads.

However, if you want to do some linq-like multi-threaded programming, you should check out the Parallel Extensions to .NET Framework. Also check out this link:

Unfortunately, this won't be RTM until VS2010/.Net4.0 is out.


Well a lambda is just an anonymous method, it is executed on whatever thread it is called on unless you provide code to execute on a separate thread.


Lambda expressions are just methods like any others. What makes a method multithreaded?

  • No access to external fields (simple input/output method) - such a method is always multithreaded
  • Accessing a synchronized field - consider synchronization scenario (Monitor class, reader/writer lock, Interlocked access, WaitHandle, etc.), minimize lock contentions.
  • Accessing a captured variable (closure) - make sure that the captured variable does not change as long as other threads use it (how the variable is accessed: just reads, reads and writes...)

The C# compiler is smart enough to know whether static or instance methods are generated for your lambdas.


Potentially confusing (but true) answer. In some commonly encountered scenarios, a lambda may execute on another machine, in a completely different kind of runtime environment, and therefore on another thread, and the caller need not necessarily wait for the remote execution to full complete before continuing.

(Specifically, if you pass it to a Linq To SQL query.)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »