v00d00
v00d00

Reputation: 3265

How to execute async operations sequentially?

Now I am using something simmilar to this construction

A.Completed += () =>
{ B.Completed += () =>
  {  C.Completed += () =>
     {
       //
     }
     C();
   }
   B();
 }  
 A();

And not very happy with it. Is there a better, more cleaner way to do such kind of sequent/concurrent action execution?

I have a look at Rx framework, but it is designed for other tasks and looks like way overkill for my problem.

Upvotes: 9

Views: 1182

Answers (5)

Timwi
Timwi

Reputation: 66573

Wait for C# 5.0 and use the new async and await keywords.

Here are a few preliminary links about this:

Upvotes: 1

DaeMoohn
DaeMoohn

Reputation: 1097

You can have a look at TPL. You can write code like in this thread: link

Upvotes: 2

Chris Pitman
Chris Pitman

Reputation: 13104

There is no need to nest setting up the Completed events, unless someone might actually call B or C before A is completed. If you separate it out, here is what it looks like:

A.Completed += () => { B(); };
B.Completed += () => { C(); };  
C.Completed += () => { //   }; 

A();

I think removing the nesting actually makes it much cleaner.

Upvotes: 8

Giorgi
Giorgi

Reputation: 30883

Have a look at ReactiveUI. It's based on Rx and will simplify your code a lot. Here is an example: Calling Web Services in Silverlight using ReactiveXaml

Upvotes: 4

Adam Rackis
Adam Rackis

Reputation: 83356

It's not much cleaner, but you might have a look at BackgroundWorker.

BackgroundWorker A = new BackgroundWorker();
A.DoWork += (s, e) => AMethod();
A.RunWorkerCompleted += (s, e) => BMethod();

BackgroundWorker B = new BackgroundWorker();
B.RunWorkerCompleted += (s, e) => CMethod();

//etc

You're not really cutting down on the code too much, but I'd say it's a lot cleaner.

Upvotes: 1

Related Questions