0

I'm writing a Xamarin.Android app (no domain knowledge is required, though). I have an async void method that looks like this:

protected override async void OnCreate(Bundle savedInstanceState)
{
    // Some synchronous code

    await SetupEditor(EditorTheme.Default);
}

I've written my app such that the task returned from SetupEditor(...) will cancel if the user clicks the back button. However, when I click the back button, the app crashes here with a TaskCanceledException. I'd like to rewrite this to

protected override async void OnCreate(Bundle savedInstanceState)
{
    // Some synchronous code

    try
    {
        await SetupEditor(EditorTheme.Default);
    }
    catch (TaskCanceledException)
    {
        return;
    }
}

Is there a more concise way to do this without using a try/catch block? I wouldn't want to write 7 lines every time I wanted to await a task like this. Thanks.

James Ko
  • 32,215
  • 30
  • 128
  • 239
  • 1
    You may of course write the extra code once, then say `await IgnoreCancelled(SetupEditor(EditorTheme.Default))`. – Ben Voigt Jul 16 '17 at 22:39
  • There are lots of ways to accomplish what you're asking. See marked duplicate for some examples. You could also do as the previous comment suggests, writing a method that just encapsulates the try/catch. At best, your question has been answered already (i.e. is a duplicate). It's also primarily opinion based ("graceful" is in the eye of the beholder") and too broad (there are many different ways to approach this type of scenario). – Peter Duniho Jul 16 '17 at 23:15
  • @PeterDuniho Thanks for your feedback. The question you linked to is not an exact duplicate of mine, however: it asks how to ignore a canceled task, whereas I'm asking how to `return` if a task is canceled. I think I found a solution using a custom awaitable that never posts the continuation if `Task.IsCanceled` is true; please un-mark this as a dupe so I can post the solution when I have time. – James Ko Jul 17 '17 at 00:30
  • @PeterDuniho Also, I've removed 'graceful' from the question; the main thing I was looking for was 'concise'. – James Ko Jul 17 '17 at 00:31

0 Answers0