Consider this piece of code:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Polly;
using Polly.Timeout;
namespace Test
{
public class Program
{
public static async Task Main()
{
var tasks = new List<Task>();
for (var i = 0; i < 20; i++)
{
var task = new Task(Test);
tasks.Add(task);
}
foreach (var task in tasks)
task.Start();
await Task.WhenAll(tasks);
}
public static void Test()
{
Console.WriteLine($"Executing Test() at {DateTime.Now}");
Policy.Timeout(TimeSpan.FromSeconds(2), TimeoutStrategy.Pessimistic)
.Execute(() => { Thread.Sleep(200); });
}
}
}
I get the following output:
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:21
Executing Test() at 2018-05-16 15:10:22
Executing Test() at 2018-05-16 15:10:23
Executing Test() at 2018-05-16 15:10:24
Executing Test() at 2018-05-16 15:10:24
Executing Test() at 2018-05-16 15:10:24
Executing Test() at 2018-05-16 15:10:25
Executing Test() at 2018-05-16 15:10:26
Executing Test() at 2018-05-16 15:10:26
Executing Test() at 2018-05-16 15:10:27
Executing Test() at 2018-05-16 15:10:27
Executing Test() at 2018-05-16 15:10:27
Executing Test() at 2018-05-16 15:10:28
And a Polly.Timeout.TimeoutRejectedException
is thrown at the very end.
I can't really understand why it would take so long to execute? From the output it seems that the first 8 tasks execute in parallel, and then it gets really slow.
Without timeout policy or with optimistic timeout strategy it runs instantly. But in my case only pessimistic timeout policy can be used.
Using the latest Polly version, which is 6.0.1.