Are lambda expressions multi-threaded?

2019-06-21 17:56发布

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?

7条回答
Root(大扎)
2楼-- · 2019-06-21 18:20

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.

查看更多
Emotional °昔
3楼-- · 2019-06-21 18:21

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.

查看更多
三岁会撩人
4楼-- · 2019-06-21 18:22

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.

查看更多
Bombasti
5楼-- · 2019-06-21 18:28

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.

查看更多
戒情不戒烟
6楼-- · 2019-06-21 18:34

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.

查看更多
走好不送
7楼-- · 2019-06-21 18:36

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.)

查看更多
登录 后发表回答