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);
}