当使用的Parallel.For?Parallel、For

2023-09-04 08:37:18 作者:天边シ深海

我最近搬到C#.NET 4。

I have recently moved to C#.net 4.

我爱的Parallel.For,但不知道何时使用,何时不。 我知道,当顺序不是对我很重要 - 我会用它

I love Parallel.For, but not sure when to use and when not to. I know that when order is not important for me - I'll use it.

但是否有关于与Parallels合作的开销任何测试?意思是,如果我的循环只运行10次(和执行非常少的逻辑) - 我应该避免的Parallels?有没有什么经验法则?

But are there any tests regarding the overhead of working with Parallels? Meaning, if my loop runs only 10 times (and performs very little logic) - should I avoid Parallels? Are there any thumb rules?

推荐答案

我会避免使用的Parallel.For ,除非性能是一个问题。

I would avoid using Parallel.For unless performance is an issue.

这同时运行在普通难度比写单线程code写作code。此外,如果你因并发性问题上做出的错误就很难进行调试。比如可能会出现的错误只是有时并不能轻易复制的。除非你在提高性能的特殊需要,我建议你保持简单,在单个线程使用普通的循环。

Writing code that runs concurrently is in general harder than writing single threaded code. Furthermore if you make an error due to a concurrency issue it can be difficult to debug it. For example the bug might occur only sometimes and not be easily reproducible. Unless you have a specific need for increased performance I would suggest that you keep it simple and use an ordinary loop on a single thread.