Task.WhenAny with cancellation of the non completed tasks and timeout

前端 未结 2 568
渐次进展
渐次进展 2020-12-20 18:03

In my app I am creating some concurrent web requests and I am satisfied when any one of them completes, so I am using the method Task.WhenAny:

var urls = new         


        
2条回答
  •  甜味超标
    2020-12-20 18:52

    Simply pass to all of your tasks the same cancellation token, something like this:

    CancellationTokenSource cts = new CancellationTokenSource();
    CancellationToken ct = cts.Token;
    // here you specify how long you want to wait for task to finish before cancelling
    int timeout = 5000;
    cts.CancelAfter(timeout);
    // pass ct to all your tasks and start them
    await Task.WhenAny(/* your tasks here */);
    // cancel all tasks
    cts.Cancel();
    

    Also, you need to read this thread to be aware of how to use CancellationToken correctly: When I use CancelAfter(), the Task is still running

提交回复
热议问题