簡體   English   中英

如何在不檢查取消掛起屬性的情況下取消異步調用(立即終止方法調用)

[英]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);
}

這是不可能的。 您可以創建一個Task ,該Task將在該現有操作完成時完成,或者在取消令牌被取消時將其自身標記為已取消,但實際上不會停止原始操作,僅允許程序繼續執行,盡管該操作確實存在尚未真正完成。

有關主題的更多信息,請參見此博客文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM