在 C# 中并行运行三种方法的最简单方法 [英] Simplest way to run three methods in parallel in C#

查看:34
本文介绍了在 C# 中并行运行三种方法的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调用了三种方法来进行一些数字运算,如下所示

I have three methods that I call to do some number crunching that are as follows

results.LeftFront.CalcAi();  
results.RightFront.CalcAi();  
results.RearSuspension.CalcAi(geom, vehDef.Geometry.LTa.TaStiffness, vehDef.Geometry.RTa.TaStiffness);

每个函数都是相互独立的,可以并行计算,没有死锁.
在所有三个都完成之前,在不包含方法完成的情况下并行计算这些的最简单方法是什么?

Each of the functions is independent of each other and can be computed in parallel with no dead locks.
What is the easiest way to compute these in parallel without the containing method finishing until all three are done?

推荐答案

请参阅 TPL 文档.他们列出了这个样本:

See the TPL documentation. They list this sample:

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

因此,在您的情况下,这应该可以正常工作:

So in your case this should just work:

Parallel.Invoke(
    () => results.LeftFront.CalcAi(),
    () => results.RightFront.CalcAi(),
    () => results.RearSuspension.CalcAi(geom, 
                                        vehDef.Geometry.LTa.TaStiffness, 
                                        vehDef.Geometry.RTa.TaStiffness));

在所有操作完成后调用返回.Invoke() 不保证它们确实会并行运行,也不保证动作执行的顺序.

The call returns after all actions have finished executing. Invoke() is does not guarantee that they will indeed run in parallel, nor does it guarantee the order in which the actions execute.

这篇关于在 C# 中并行运行三种方法的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆