繁体   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