New Thread Error Handling

NicoleNicole USMember

I'm a bit stuck on how to do proper error handling here:

MenuScreen.RequestSettings requests settings from our server using Service Stack. This works fine when the application has access to the server and everything is configured, but if anything goes wrong (which is likely to happen), my app crashes. I need a way to handle the error that occurs. I have done a try catch around this code and also within the RequestSettings call. I feel like I'm missing something really obvious, thoughts?

new Thread(new ThreadStart(delegate
{
RunOnUiThread(MenuScreen.RequestSettings);
// additional code removed for clarity
})).Start();

I am calling this on a new thread due to a recommendation I found elsewhere that any calls that may take a bit should not be on the current thread or my application will look like it locked up.

Thank you!

Posts

  • JohnMillerJohnMiller Xamurai USForum Administrator, Xamarin Team Xamurai

    Hey @Nicole,

    I grabbed your example code and modified it slightly to this for a test:

    var progressDialog = new ProgressDialog (this);
    progressDialog.SetMessage ("Contacting Server...");
    progressDialog.Show ();
    
    new Thread (new ThreadStart (delegate {
        RunOnUiThread(() => { // Like your MenuScreen.RequestSettings method
            try { // Exception handling inside this method
                throw new Exception("Oops!"); 
            } catch (Exception ex) {
                Console.WriteLine(ex.Message); // We hit this and all is good
                progressDialog.Dismiss();
            }
        });
    })).Start ();
    

    Adding a try/catch inside the Action that RunOnUiThread() is running did work for me. If this does not work for you, could you show how you implemented exception handling in your MenuScreen.RequestSettings method?

    Thanks!
    John

  • CheesebaronCheesebaron mod DKInsider, University mod

    Why aren't you using await/async and Tasks instead? It will lead to a lot less bloated code...

Sign In or Register to comment.