Forum Cross Platform with Xamarin

generic web service calls and exception handling

hi guys,

I came up with an advanced topic, when I did some review on my source code.

I figured, that I use double code when it comes to asynchronously calling web service methods using BackgroundWorkers.

When you have a look at the code you see, that its basically every time the same code, only three parts are different:
1) the ws method I'm calling
2) the actions I do when the web service call was successful and
3) the actions I do when a SoapException occurred.
4) the message that shall be displayed on the LoadingOverlay

So my target is to find a generic solution for that.

This is the corresponding code:

` Exception exception = null;
BackgroundWorker bw = new BackgroundWorker ();

            bw.DoWork += (object sender, DoWorkEventArgs e) => {

                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;

                try {
                    // here I want to call the webservice method                    }
                catch(Exception ex) {
                    exception = ex;

            bw.RunWorkerCompleted+= (object sender, RunWorkerCompletedEventArgs e) => {

                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;

                if(exception == null) {
                    // here I want to do some custom actions
                else if(exception is WebException) { 
                    // here I want to show always the same message in an uialertview
                else if(exception is SoapException) { 

                    // here I want to do some custom actions
                else { 
                    // here I want to show always the same message in an uialertview

            loadingOverlay = new LoadingOverlay(//string with the message that shall be displayed));


Hope you can help me out :)


  • YSharpYSharp USMember ✭✭
    edited January 2014

    That might be a good use case of implementing the strategy pattern:

    If you pick that pattern, I'd recommend that the classes that will implement the concrete strategy(ies) be either stateless, or immutable "at the most" (i.e., readonly fields initialized from some config in its(their) constructors, etc).

    Anyhow, don't forget about the ambient thread safety aspect if anything has to be created before the call to your BGWorker.DoWork and accessed + mutated afterwards (during DoWork's execution).

    You'll also probably need a factory somewhere (or just rely on Activator.CreateInstance, which might just be enough).


Sign In or Register to comment.