TimeoutUtils.cs 1011 B

123456789101112131415161718192021222324252627282930
  1. namespace qdr.fnd.core.pqueue.fnd.candidates
  2. {
  3. public class TimeoutUtils
  4. {
  5. public static async Task ExecuteWithTimeoutAsync(Action action, TimeSpan timeout)
  6. {
  7. using var cts = new CancellationTokenSource();
  8. var task = Task.Run(action, cts.Token);
  9. try
  10. {
  11. if (await Task.WhenAny(task, Task.Delay(timeout, cts.Token)) == task)
  12. {
  13. // Task completed within the timeout
  14. await task; // Propagate any exceptions
  15. }
  16. else
  17. {
  18. // Timeout occurred
  19. cts.Cancel();
  20. throw new TimeoutException($"The operation has timed out after {timeout.TotalSeconds} seconds.");
  21. }
  22. }
  23. finally
  24. {
  25. cts.Cancel(); // Ensure we always cancel the CancellationTokenSource
  26. }
  27. }
  28. }
  29. }