c# - How to return the not-cancelled tasks from Task.WhenAll execution
问题描述
I have a list of tasks that are cancellable; they have their CancellationTokenSource
. Their cancellation is independent of others. I want to return all the not-canceled tasks from Task.WhenAll
.
var tasks = new List<Task<string>>();
/** some code here **/
var done = await Task.WhenAll(tasks); // This throws an OperationCanceledException,
// when at least one task is cancelled.
There are questions in the StackOverflow "how to cancel a task inside a task," but this question here is not that.
解决方案
You can retry the rest of the tasks by looping Task.WhenAll
var tasks = new List<Task<string>>();
/** some code here **/
var notCanceled = tasks;
do
{
try
{
await Task.WhenAll(notCanceled);
break;
}
catch (OperationCanceledException)
{
notCanceled = notCanceled.Where(t => !t.IsCanceled).ToArray();
}
} while (notCanceled.Any())
推荐阅读
- java - 方块纹理仅在放置时丢失
- c# - C#如何从派生类调用接口方法
- sparql - SPARQL CONSTRUCT subClassOf
- android - 如何访问 android 11 (Scoped storage) 中的 whatsapp/media 目录?
- r - 如何使用 R 中的 for 循环将多个栅格裁剪到相同程度?
- python - 使用烧瓶引导程序时烧瓶错误查找模板
- machine-learning - 为什么正则化不能接受 Φ 作为惩罚参数?
- c - 如何在 pthread_create() C 编程语言中传递多个参数
- assembly - 如何通过将密码更改为 * 来隐藏/保护密码
- css - 打印时,break-inside 在随机位置创建一个空间并仍然破坏元素