Handle cancellation of async method

后端 未结 1 614
广开言路
广开言路 2021-01-06 14:23

I\'m using Parse as a data store for an app, and I am implementing their Facebook Login functionality. AFAIK, this Login method isn\'t any different than other async methods

相关标签:
1条回答
  • 2021-01-06 15:04

    Never have async void methods. You cannot handle exceptions properly in them. If your async method does not return anything use async Task (not generic) as the return type instead.

    You can then await on your returned Task to handle the exceptions properly.

    If you are going to set use CancellationTokens make your you pass your CancellationTokenSource's token to the async method. You can then register this token either to a callback or continue to pass the token into the LoginAsync method if that overload is available. I used this MSDN article to get myself familiar with the cancellation methods.

    Also take a look at this article from the MSDN blog in regards to avoiding the async void issues: Async-Await Best Practices

    EDIT
    Per the edit in your question I wanted to point something out. If you call

    Task<ParseUser> t = FacebookLogin()
    

    You now have a Task object that you can do stuff with. However, if you just want the ParseUser object and have no continuations or need to do anything else with the Task you should use await once again.

    ParseUser p = await FacebookLogin();
    

    Since this is in an event handler (loaded) it is the one exception where it's OK to have an async void

    As to what happens when you a cancellation occurs, well that's up to you. You can close the login window, cancel other tasks/methods, etc.

    0 讨论(0)
提交回复
热议问题