How to cancel a task using a CancellationToken and await Task.WhenAny

浪子不回头ぞ 提交于 2021-01-28 07:54:32

问题


I have web application and it calls different web service to perform different work. Some web services will take long time and some short. Application will call all web services parallel to get result when complete or exception. I have started to write code but i need to know how to implement the following works in the best way.

  1. A task will be cancelled if any of web service takes more than 5 seconds but remaining tasks will continue to call web service to get either result or excepton.
  2. I used CancellationTokenSource in my sample code but OperationCanceledException does not catch. It goes to exception catch always.
  3. Is it best practice to limit number of thread to execute my web services? if so, how can i limit threads and reuse them.

Any sample code or url will help me.

protected async void btnAAC_Click(object sender, EventArgs e)
{
    CancellationTokenSource cts = new CancellationTokenSource();
    cts.CancelAfter(5000); 
    string[] retResult = null;

    Task<string[]> taskResult = Run(cts.Token); 

    try
    {
        retResult = await taskResult;
        //To do : display data
    }
    catch (OperationCanceledException ocex)
    {
        resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
    }
    catch(Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
    finally
    {
        cts.Dispose();
    }  
}

private async static Task<string[]> Run(CancellationToken cancellationToken)
{
    HashSet<Task<string>> tasks = new HashSet<Task<string>>();
    List<string> urlList = ServiceManager.SetUpURLList();
    List<string> finalResult = new List<string>();

    foreach (var work in urlList)
    {
        tasks.Add(Task.Run(() => DoWork(work, cancellationToken)));
    }

    try
    {
        while (tasks.Count > 0)
        {
            Task<string> finishedTask = await 
                    Task.WhenAny(tasks.ToArray());
            tasks.Remove(finishedTask);
            finalResult.Add(finishedTask.Result);
        }

        return finalResult.ToArray();
    }
    finally
    {
        //CleanUpAfterWork();
    }
}

public async static Task<string> DoWork(string url, CancellationToken cancellationToken)
{
    while (true)
    {            
        cancellationToken.ThrowIfCancellationRequested();

        var html = await Downloader.DownloadHtml(url);

        return html;
    }
}

回答1:


A task will be cancelled if any of web service takes more than 5 seconds but remaining tasks will continue to call web service to get either result or excepton.

The following code sample contains one approach (and a Fiddle). Its RunTimeLimitedTask method contains the key parts of the strategy.

public static void Main()
{
    DoIt().GetAwaiter().GetResult();
}

public async static Task DoIt() 
{
    var results = await Task.WhenAll(
        RunTimeLimitedTask(10),
        RunTimeLimitedTask(1000));

    foreach(var result in results) Console.WriteLine(result);
}

public async static Task<string> RunTimeLimitedTask(int timeLimit)
{
    // A
    var source = new CancellationTokenSource();
    source.CancelAfter(timeLimit);

    // B
    try {
        await Task.Run(async () => await Task.Delay(500, source.Token));

         // C
        return "Complete";
    }
    catch (TaskCanceledException) {
        // C
        return "Cancelled";
    }
}

A: create a new time-limited CancellationSource for each web request.

B: wrap the awaited web request (which we mimic with a delayed Task) in a try catch block that handles the TaskCanceledException.

C: Handle both the success and the cancellation by returning a string that communicates the success/failure. To make that strategy better, return something with more structure, such as a Result<TSuccess, TFailure> instead of returning a string.



来源:https://stackoverflow.com/questions/49588228/how-to-cancel-a-task-using-a-cancellationtoken-and-await-task-whenany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!