gpt4 book ai didi

c# - 如何在调用 Task.WaitAll 之前了解异常?

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:32 26 4
gpt4 key购买 nike

就我而言,我通过以下方式创建了任务:

IList<Task> Tasks = new List<Task>();
Tasks.Add(Task.Run(async () => { await functionAsync();}));

我需要这些任务无限运行,以便持续处理一些传入数据。但是,如果发生某些 fatal error /异常,我需要通过取消所有任务来结束程序。我整理了一个简单的例子来模拟我打算做什么,但它不起作用。我认为当抛出异常时任务将被视为结束,并且 WaitAny 应该返回 AggregatedException,但它似乎并不是它实际工作的方式。那么,我怎样才能让它正确呢?

public static void Main(string[] args)
{
Console.WriteLine(nameof(Main));
for (int i = 1; i < 5; i++)
{
var i1 = i;
_tasks.Add(Task.Run(async () => { await Tryme(i1); }));
}

try
{
Task.WaitAny(_tasks.ToArray());
}
catch (Exception e)
{
Console.WriteLine("Stop my program if any of the task in _tasks throw exception");
Console.WriteLine(e);
}
Console.ReadLine();
}

private static async Task Tryme(int i)
{

Console.WriteLine($"I'm {i}");
if (i == 3)
{
Console.WriteLine($"{i} is throwing the exception");
throw new Exception("fake one");
}
await Task.Delay(TimeSpan.MaxValue);
}

最佳答案

无需手动取消整个任务链,您可以使用 TPL Dataflow如果发生未处理的异常,它会为您停止整个 block ,或者可以配置为在 other modes 中运行如果需要:

var actionBlock = new ActionBlock<int>(i => TryMe(i));

foreach (var num in Enumerable.Range(0, 100))
{
actionBlock.Post(num);
}

try
{
await actionBlock.Completion();
}
catch (Exception e)
{
// Block finished prematurely, handle exception.
}

注意 Dataflow 会为您处理并行化,无需手动创建任务。

关于c# - 如何在调用 Task.WaitAll 之前了解异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33640522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com