Is there a useful design pattern for chained asynchronous / event calls?

I currently have to integrate a lot of web service calls into Silverlight, which make the calls look like the code below. No user interaction should be possible until the download of all 3 has been completed.

// In my view, having standard delegate methods (non-anonymous) makes the // code below even messier. // I've left out the EventArgs to shorten the example however // I usually use these objects in the delegate method. MyService1 service1 = new MyService1(); service1.GetAllUsersCompleted += delegate { MyService2 service2 = new MyService2(); service2.AnotherTaskCompleted += delegate { MyService3 service3 = new MyService3(); service3.YetAnotherTaskCompleted += delegate { // etc. }; service3.YetAnotherTask(); }; service2.AnotherTask(); }; service1.GetAllUsers(); 

Essentially, I would like the calls to be synchronous due to the architecture of the web service proxy classes in Silverlight (everything is related to events). I can not do it.

My question is, is there a more elegant solution, or maybe a .NET design template for refactoring what I have from one delegate method calling another method calling another into something that is easier to manage?

One of my biggest problems with the code is calling the actual method that comes after the main work in deletion.

+2
c # design-patterns anonymous-methods delegates
source share
3 answers

Well, I would first recommend that you use the asynchronous nature of Silverlight, making all three calls at once, if possible.

You can do this โ€œsequentiallyโ€ with tasks (in particular, continuing tasks), but you can also look at the Rx library , which is designed to correctly manage this situation.

One last tip: prohibiting user interaction is not recommended. At least give them the opportunity to cancel the operation.

+2
source share

I think this is what the new Task classes (in the parallel library) are trying to abstract, but I could be wrong :)

+1
source share

Maybe I'm wrong, but no delegates are already synchronous. You can make them asynchronous using the BeginInvoke method. Here is a good resource for synchronous and asynchronous method calls and explains some patterns, etc. http://support.microsoft.com/kb/315582

The title of the article could be: How to call a Visual C # method asynchronously, but there is an example of synchronous method calls about halfway.

0
source share

All Articles