[英]How to cancel an async call without checking the cancellation pending property (Instantly terminating the method call)
我找不到取消在后台线程上运行的异步调用的方法。 假设我有这样的事情:
private async void myMethod()
{
String result = await Task.Run(async () => await myTimeConsumingMethod());
//Do stuff with my result string...
}
在这里,我在后台线程上调用了一个异步方法,并且由于我没有任何循环,所以无法执行以下操作:
for (i = 0; i < someBigNumber; i++)
{
token.ThrowIfCancellationRequested();
await doSomeWork();
}
取而代之的是,我只有一个异步方法调用,可能要花费10秒钟以上的时间才能完成,但是我无法检查该方法内部的令牌是否已取消,因为我正在等待异步调用完成。
这是我要实现的目标:
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.
}
问题是我不知道在HardwareButtons.BackPressed
事件内使用什么代码来终止我的异步调用。 我的意思是,我确实想“终止其过程”并使该Task.Run立即返回null。
有没有办法做到这一点?
这是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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.