0

I can't seem to get the below code to result in cancelling the GetAsync(). It continues to fetch the file. I setup this colours-like diagnostic and can see things happening the way they should (click events raises cancel, the progress frame elsewhere on the screen goes yellow, green and red happen as they should).

cts = new System.Threading.CancellationTokenSource(); //declared earlier...
var token = cts.Token;

BackgroundColor = Color.Red;
try
{
    var fileContent = await 

    App.GraphClient.Me.Drive.Root.ItemWithPath(App.selectedOneDriveFolder + "/" + item.path).Content.Request().GetAsync(token);
    // Do nothing with fileContent... this is just for testing
}
catch (Exception ex)
{
    await DisplayAlert("Cancelled finally?", ex.Message, ":(");
}

BackgroundColor = Color.Green;
//and then the clicked event handler...

private void CancelDownloadButton_Clicked(object sender, EventArgs e)
{
    cts?.Cancel();
    ProgressFrame.BackgroundColor = Color.Yellow;
}

I also tried all sorts of different versions of running this (with Task, with .Run and/or .Wait(token)), but to no avail. Any ideas?

GSerg
  • 76,472
  • 17
  • 159
  • 346
Elbowz
  • 76
  • 4
  • It is the harsh thruth that not infrequently these nice interfaces simply ignore the cancellation token, e.g. see https://stackoverflow.com/q/12421989/11683. – GSerg May 25 '20 at 18:18
  • That's sad. So how do you cancel a download of a big file without having to reinvent the wheel and write a bunch of code that would fetch a small chunk of remote file and then test for cancellation event before fetching the next chunk? – Elbowz May 25 '20 at 18:47
  • You can't cancel an already launched asynchronous operation that was not designed to support cooperative cancellation in the first place, unless you kill the process (and even this may not be enough in some cases). – Theodor Zoulias May 25 '20 at 20:57
  • @TheodorZoulias You can however make it impossible for the launched operation to proceed which will *make* it stop. E.g. in the case of a network stream linked to above, they close the stream from under the async operation. – GSerg May 26 '20 at 06:57
  • @GSerg you are right. Closing a `Stream` or disposing an `HttpClient` can be an option. I should keep that in mind. :-) – Theodor Zoulias May 26 '20 at 07:15
  • It just doesn't seem to work. I declared Stream variable globally, then attempt to close the stream at the press of a button in my Clicked event, but even though close() method is called, it just hangs in there until the original GetAsync returned. I can see the call to Clicked event happens instantaneously but the download continues regardless. – Elbowz May 26 '20 at 19:45

0 Answers0