简体   繁体   中英

How to cancel an async call without checking the cancellation pending property (Instantly terminating the method call)

I can't find a way to cancel an async call running on the background thread. Let's say I have something like this:

private async void myMethod()
{
    String result = await Task.Run(async () => await myTimeConsumingMethod());
    //Do stuff with my result string...
}

Here I'm calling an async method on my background thread, and since I don't have any loops I can't do something like this:

for (i = 0; i < someBigNumber; i++)
{
    token.ThrowIfCancellationRequested();
    await doSomeWork();
}

Instead I have a single call to an async method that can take more than 10 seconds to complete, I can't check if the token has been canceled inside that method, since I'm awaiting for the async call to complete.

This is what I'm trying to achieve:

private async void myMethod()
{
    String result = await Task.Run(async () => await myTimeConsumingMethod());

    //Override the HardwareButtons.BackPressed event (I already have a method for that)

    //When the await is completed, the String is the result of the async 
    //call if the method has completed, otherwise the result String 
    //should be set to null.
}

The problem is that I don't know what code to use inside the HardwareButtons.BackPressed event to terminate my async call. I mean, I literally want to "terminate its process" and make that Task.Run instantly return null.

Is there a way to do that?

This is the implementation of myTimeConsumingMethod():

public static async Task<String> ToBase64(this StorageFile bitmap)
{
    IRandomAccessStream imageStream = await CompressImageAsync(bitmap);
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);
    PixelDataProvider pixels = await decoder.GetPixelDataAsync();
    byte[] bytes = pixels.DetachPixelData();
    return await ToBase64(bytes, (uint)decoder.PixelWidth, (uint)decoder.PixelHeight, decoder.DpiX, decoder.DpiY);
}

This is impossible. You can create a Task that will complete when that existing operation completes, or mark itself as cancelled if a cancellation token is cancelled, but that won't actually stop the original operation, merely allow the program to continue executing despite the fact that the operation isn't actually done yet.

See this blog article for more information on the subject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM