如果当前 运行 任务发生异常,则停止 semphore 任务执行

Stop semphore task execution if exception occurs in current running task

我有以下测试代码来模拟使用信号量和节流任务执行。如果 运行 任务之一抛出如下异常,是否有办法不继续创建新任务。我不需要现有任务停止运行,我只是希望遇到异常后不启动新任务。

目前任务都会在下面这个场景中开始。由于抛出异常,我希望它在一些任务 运行 后停止。

            var testStrings = new List<string>();
            for (var i = 0; i < 5000; i++)
            {
                testStrings.Add($"string-{i}");
            }

            using (var semaphore = new SemaphoreSlim(10))
            {
                var tasks = testStrings.Select(async testString =>
                {
                    await semaphore.WaitAsync();
                    try
                    {
                        Console.WriteLine($"{testString}-Start");
                        await Task.Delay(2000);
                        throw new Exception("test");
                    }
                    finally
                    {
                        semaphore.Release();
                    }
                });

                await Task.WhenAll(tasks);
            }

根据 Sinatr 的评论,我认为通过添加要监视的取消令牌这可能对我有用。

       var testStrings = new List<string>();
        for (var i = 0; i < 5000; i++)
        {
            testStrings.Add($"string-{i}");
        }

        var cancellationTokenSource = new CancellationTokenSource();
        var cancellationToken = cancellationTokenSource.Token;

        using (var semaphore = new SemaphoreSlim(10))
        {
            var tasks = testStrings.Select(async testString =>
            {
                    await semaphore.WaitAsync();
                    try
                    {
                       if (!cancellationToken.IsCancellationRequested)
                       {
                           Console.WriteLine($"{testString}-Start");
                           await Task.Delay(2000);
                           throw new Exception("test");
                       }
                    }
                    catch (Exception ex)
                    {
                        if (!cancellationTokenSource.IsCancellationRequested)
                            cancellationTokenSource.Cancel();
                        throw;
                    }
                    finally
                    {
                        semaphore.Release();
                    }
            });

            await Task.WhenAll(tasks);
        }