[英]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.