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 开发者_StackOverflow社区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.
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.
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
You can have a look at TPL. You can write code like in this thread: link
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.
Wait for C# 5.0 and use the new async
and await
keywords.
Here are a few preliminary links about this:
“Simplifying Asynchrony – That for which we await”, Reed Copsey, Jr.
“C# Async”, csharphelp.com
“Initial thoughts on C# 5's async support”, John Skeet
精彩评论