2

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 ?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Chakkara S
  • 21
  • 2
  • 1
    This is more of a `TPL`/`Parallel` question than Rx - there's no real need for "push-based" functionality here. – JerKimball Mar 04 '13 at 17:20

4 Answers4

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

result.Subscribe(x => Console.WriteLine(x));
Ana Betts
  • 73,868
  • 16
  • 141
  • 209
  • 1
    This (or replacing `Zip` with `CombineLatest`) is probably the most straightforward answer, although I still maintain you don't *need* to use Rx for this :) – JerKimball Mar 04 '13 at 18:43
0

You could use zip method to achive needed behaviour.

Denys Denysenko
  • 7,598
  • 1
  • 20
  • 30
-1

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

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
-1

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);
Community
  • 1
  • 1
Tim
  • 960
  • 5
  • 19