TimeoutUtils.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233
  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. catch(Exception){
  24. throw;
  25. }
  26. finally
  27. {
  28. cts.Cancel(); // Ensure we always cancel the CancellationTokenSource
  29. }
  30. }
  31. }
  32. }