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?
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?
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.
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.
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 expreience the are much less likely to be thread safe than you would expect.
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:
http://blogs.msdn.com/pfxteam/
Unfortunately, this won't be RTM until VS2010/.Net4.0 is out.
Lambda expressions are just methods like any others. What makes a method multithreaded?
Monitor
class, reader/writer lock, Interlocked
access, WaitHandle
, etc.), minimize lock contentions.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.)