使用Reactive以并行方式运行方法

晕到那里,我一直在寻找RX框架的解决方案。 我的C#4.0类将调用2种不同的方法并节省时间,我想并行执行。 有没有办法使用Reactive Framework并行运行2种不同的方法? 不仅要并行运行这两个方法,还要等待其他方法完成并合并两个结果。 示例如下图所示:

AccountClass ac = new AccountClass(); string val1 = ac.Method1(); bool val2 = ac.Method2(); 

如何运行这两个方法并行运行并相互等待完成并在Subscription部分中将结果组合在一起?

 var result = Observable.Zip( Observable.Start(() => callMethodOne()), Observable.Start(() => callMethodTwo()), (one, two) => new { one, two }); result.Subscribe(x => Console.WriteLine(x)); 

您可以使用zip方法来实现所需的行为。

与Rui Jarimba相似,但更简洁;

  string val1 = null; bool val2 = false; Action action1 = () => { val1 = ac.Method1(); }; Action action2 = () => { val2 = ac.Method2(); }; Parallel.Invoke(new ParallelOptions(), action1, action2); 

试试这个:

 using System.Threading.Tasks; string val1 = null; bool val2 = false; var actions = new List(); actions.Add(() => { val1 = ac.Method1(); }); actions.Add(() => { val2 = ac.Method2(); }); Parallel.Invoke(new ParallelOptions(), actions.ToArray()); // alternative - using Parallel.ForEach: // Parallel.ForEach(actions, action => action()); // rest of your code here..... 

有用的链接:

http://tipsandtricks.runicsoft.com/CSharp/ParallelClass.html