Serberuss
Serberuss

Reputation: 2387

Web Service Controller Design

In a splash screen for an iOS app written in MonoTouch C# I am calling a number of web services which then calls another web service until all the data I need has been collected for the app to run. I am doing this asynchronously so that I can display an activity indicator to the user.

However I feel like the code is very messy and all these calls and callbacks are in the ViewController. I would like a way of separating this so that the ViewController only cares about the results coming back but I would need a way for the ViewController to stop until the call has completed.

At the moment, my code looks a little something like this:

protected void FirstServiceCompleted(object sender, FirstServiceCompletedEventArgs e)
{
    // Do something
    _servicesHelper.GetSecondService(GetSecondServiceCompleted);
}

protected void SecondServiceCompleted(object sender, SeconServiceCompletedEventArgs e)
{
    // Do something else
    _servicesHelper.GetThirdService(GetThirdServiceCompleted);
}

... etc

It would be nice to have a way which through another object my ViewController retrieves the data from the event args while behind the scenes I use this code. At the end of all these calls I change to a new view to show the main home screen with this data populated. However my ViewController seems very bloated and there's a lot of repetitive calls like this.

Any help or advice would be very much appreciated.

Upvotes: 1

Views: 197

Answers (1)

Stuart
Stuart

Reputation: 66882

I think it might be useful for you to look at the TPL - Task Parallel Library - this tackles exactly the sort of async processing you are talking about.

Using Task along with ContinueWith and WaitAll, I'm sure you'll find a way to clean up your code flow.

If you search you'll find hundreds of getting started links for this - eg http://www.codeguru.com/columns/experts/article.php/c17197/Understanding-Tasks-in-NET-Framework-40-Task-Parallel-Library.htm


Built on top of the TPL, in the near future you will also be able to use the new await/async features of c# - but these aren't available today for MonoTouch.

Upvotes: 2

Related Questions