Starting and cancelling an asynchronous task

I have a XAML-based Xamarin.Forms page with some buttons bound to commands (implementations of the “System.Windows.Input.ICommand” interface) defined as properties of my ViewModel, which is in the BindingContext of the page. I need to be able to use one button to invoke a method of the ViewModel calling an async method (with “await”) from a referenced library (I cannot modify this method) and to use another button to cancel the async method from the referenced library if its execution lasts too long. What is the best way to achieve this?

Answers

  • TorbenKruseTorbenKruse DEMember ✭✭✭
    edited September 2015

    Should be something like this:

    CancellationTokenSource cts = new CancellationTokenSource();
    cts.CancelAfter(5000);
    
    await Task.Run(() => {  }, cts.Token);
    
    if (cts.Token.IsCancellationRequested)
    {
        // cancelled
    }
    
  • adamkempadamkemp USInsider, Developer Group Leader mod

    Using a CancellationToken is the right approach, but it requires that the async method you're calling supports cancellation. There is no magic bullet here. You can't cancel an async task that doesn't support cancellation.

Sign In or Register to comment.