Cancel Cancel Asynchronous Method

I use Parse as the data store for the application, and I implement them on Facebook Login . AFAIK, this login method is no different from other async methods, so I hope it is applicable.

So, there is the Login.xaml page that has the “Login with Facebook” button, and clicking this button will lead you to the FacebookLogin.xaml page, which contains only the control WebBrowserin accordance with the related documentation. In ContentPanel.Loadedon FacebookLogin.xaml, I can use the following code to login:

async void FacebookLogin()
{
   try
   {
      user = await ParseFacebookUtils.LogInAsync(fbBrowser, new[] { "user_likes", "email" });
   }
   catch (OperationCanceledException oce)
   {
      // task was cancelled, try again
      //task = null;
      //FacebookLogin();
   }
   catch (Exception ex)
   {
   }
}

, , . , ( async), , , Facebook.

, OperationCancelledException, , . :

  • catch OperationCanceledException WebBrowser . .

  • catch FacebookLogin(), . .

  • await Task<ParseUser>, , .

-, , CancellationToken, ? , Facebook, "".

:

, @JNYRanger, . , , , . FacebookLogin.xaml:

public partial class LoginFacebook : PhoneApplicationPage
{
   Task<ParseUser> task;
   CancellationTokenSource source;

   public LoginFacebook()
   {
      InitializeComponent();
      ContentPanel.Loaded += ContentPanel_Loaded;
   }

   async void ContentPanel_Loaded(object sender, RoutedEventArgs e)
   {
        try {
          source = new CancellationTokenSource();
          task = ParseFacebookUtils.LogInAsync(fbBrowser, new[] { "user_likes" }, source.Token);
          await task;

          // Logged in! Move on...
       }
       catch (Exception ex) { task = null; }     
   }

   protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
   {
       if (task != null) source.Cancel(false);
       base.OnBackKeyPress(e);
   }
}

, "", CancellationToken , . , task null. , FacebookLogin ( ), task .

+3
1

async void. . async , async Task ( ) .

, Task .

CancellationTokens, CancellationTokenSource async. , LoginAsync, . MSDN, .

MSDN, async void: Async-Await Best p >


-.

Task<ParseUser> t = FacebookLogin()

Task, . , ParseUser - Task, await.

ParseUser p = await FacebookLogin();

(), , async void

, , , , . , / ..

+4

All Articles