1

我想使用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;
}
4

2 回答 2

5

我想使用 CancellationToken 中止文件下载

下载文件是一种 I/O 操作,在 .NET 平台上可以使用异步可取消(基于 I/O 完成端口)功能。然而你似乎没有使用它们。

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

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

您可以执行以下操作:

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());
    }
}
于 2015-05-05T14:03:43.247 回答
0

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

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

作为对调用方法和 之间管道的快速测试CancellationToken,您可以更改GetDocumentAsync为:

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

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

[编辑]

鉴于您对问题的编辑,最快的解决方法是将CancelTokendown 传递给WsGetResponseString并使用CancelToken.Register()to call WebRequest.Abort()

你也可以CancelAfter()用来实现你的 50 秒超时,切换BeginGetResponse..EndGetResponseGetResponseAsync等。

于 2015-05-05T13:32:49.487 回答