Run methods in Parallel using Reactive

时光怂恿深爱的人放手 提交于 2020-01-01 06:53:08

问题


Halo there all, I was looking for a solution with RX framework. My C# 4.0 class is going to call 2 different methods and to save the time, I want to do it in parallel. Is there any way to run 2 different methods in parallel using Reactive Framework ? Not only run those 2 methods parallel, but also one should wait for other to complete and combine the both results. Example as shown below:

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

How I can run these 2 methods run in parallel and waits each other to complete and combine the results together in the Subscription part ?


回答1:


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

result.Subscribe(x => Console.WriteLine(x));



回答2:


You could use zip method to achive needed behaviour.




回答3:


Similar to Rui Jarimba, but a bit more succinct;

        string val1 = null;
        bool val2 = false;

        Action action1 = () =>
        {
            val1 = ac.Method1();
        };

        Action action2 = () =>
        {
            val2 = ac.Method2();
        };

        Parallel.Invoke(new ParallelOptions(), action1, action2);



回答4:


Try this:

using System.Threading.Tasks;


string val1 = null;
bool val2 = false;

var actions = new List<Action>();

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

Helpful link:

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



来源:https://stackoverflow.com/questions/15203445/run-methods-in-parallel-using-reactive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!