繁体   English   中英

使用CancellationToken进行异步/等待不会取消操作

[英]Async/await with CancellationToken doesn't cancel the operation

我想使用CancellationToken中止文件下载。 这是我尝试的:

public async Task retrieveDocument(Document document)
{
    // do some preparation work first before retrieving the document (not shown here)
    if (cancelToken == null)
    {
        cancelToken = new CancellationTokenSource();
        try
        {
            Document documentResult = await webservice.GetDocumentAsync(document.Id, cancelToken.Token);
            // do some other stuff (checks ...)
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("abort download");
        }
        finally
        {
            cancelToken = null;
        }
    }
    else
    {
        cancelToken.Cancel();
        cancelToken = null;
    }
}

public async Task<Document> GetDocumentAsync(string documentId, CancellationToken cancelToken)
{
    Document documentResult = new Document();

    try
    {

        cancelToken.ThrowIfCancellationRequested();

        documentResult = await Task.Run(() => manager.GetDocumentById(documentId));
    }

    return documentResult;
}

cancelToken然后应用于取消操作:

public override void DidReceiveMemoryWarning ()
{
    // Releases the view if it doesn't have a superview.
    base.DidReceiveMemoryWarning ();

    if (cancelToken != null) {
        Console.WriteLine ("Token cancelled");
        cancelToken.Cancel ();
    }
}

似乎IsCancellationRequested没有更新。 因此操作不会被取消。 我也试图用这个

cancelToken.ThrowIfCancellationRequested();
try{
    documentResult = await Task.Run(() => manager.GetDocumentById (documentId), cancelToken);
} catch(TaskCanceledException){
    Console.WriteLine("task canceled here");
}

但是什么都没有改变。

我做错了什么?

编辑:

以下是缺少的部分,例如GetDocumentById

public Document GetDocumentById(string docid)
{
    GetDocumentByIdResult res;
    try
    {
        res = ws.CallGetDocumentById(session, docid);
    }
    catch (WebException e)
    {
        throw new NoResponseFromServerException(e.Message);
    }

    return res;
}

public Document CallGetDocumentById(Session session, string parmsstring)
{
    XmlDocument soapEnvelope = Factory.GetGetDocumentById(parmsstring);
    HttpWebRequest webRequest = CreateWebRequest(session);
    webRequest = InsertEnvelope(soapEnvelope, webRequest);
    string result = WsGetResponseString(webRequest);
    return ParseDocument(result);
}

static string WsGetResponseString(WebRequest webreq)
{
    string soapResult = "";
    IAsyncResult asyncResult = webreq.BeginGetResponse(null, null);
    if (asyncResult.AsyncWaitHandle.WaitOne(50000))
    {
        using (WebResponse webResponse = webreq.EndGetResponse(asyncResult))
        {
            if (webResponse != null)
            {
                using (var rd = new StreamReader(webResponse.GetResponseStream()))
                {
                    soapResult = rd.ReadToEnd();
                }
            }
        }
    }
    else
    {
        webreq.Abort();
        throw new NoResponseFromServerException();
    }

    return soapResult;
}

我想使用CancellationToken中止文件下载

下载文件是一项I / O操作,.NET平台上提供了异步可取消(基于I / O完成端口)功能。 但是您似乎并没有使用它们。

相反,您似乎正在使用执行阻塞I / O的Task.Run创建(一系列)任务,其中取消令牌没有传递到Task.Run链中的每个任务。

有关执行异步,等待和可取消文件下载的示例,请参考:

  • 使用HttpClient如何异步复制和取消HttpContent?
  • Windows Phone在Windows Phone 8中下载并保存文件异步
  • 使用WebClient :有其自己的取消机制: CancelAsync方法,您可以使用令牌的Register方法将其连接到取消令牌:
      myToken.Register(myWebclient.CancelAsync); 
  • 使用抽象的WebRequest :如果不是使用附加的取消令牌创建的(如您所编辑的示例那样),并且您实际上并未下载文件,而是读取内容字符串,则需要使用前面提到的几种方法。

您可以执行以下操作:

static async Task<string> WsGetResponseString(WebRequest webreq, CancellationToken cancelToken)`
{
    cancelToken.Register(webreq.Abort);
    using (var response = await webReq.GetResponseAsync())
    using (var stream = response.GetResponseStream())
    using (var destStream = new MemoryStream())
    {
        await stream.CopyToAsync(destStream, 4096, cancelToken);
        return Encoding.UTF8.GetString(destStream.ToArray());
    }
}

您的代码在启动GetDocumentAsync方法后仅调用ThrowIfCancellationRequested()一次,这使得捕获取消的窗口非常小。

您需要将CancellationToken传递给GetDocumentById,并ThrowIfCancellationRequested在操作之间调用ThrowIfCancellationRequested ,或者将令牌直接传递给较低级别​​的某些调用。

为了快速测试调用方法和CancellationToken之间的关系,您可以将GetDocumentAsync更改为:

cancelToken.ThrowIfCancellationRequested();
documentResult = await Task.Run(() => manager.GetDocumentById(documentId));
cancelToken.ThrowIfCancellationRequested();

并在创建CancellationTokenSource之后立即调用CancelToken.CancelAfter(50)或类似方法...您可能需要根据GetDocumentById运行多长时间来调整值50。

[编辑]

根据您对问题的编辑,最快的解决方法是将CancelToken向下传递给WsGetResponseString并使用CancelToken.Register()调用WebRequest.Abort()

您还可以使用CancelAfter()来实现您的50秒超时,从BeginGetResponse..EndGetResponse切换到GetResponseAsync等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM