C# RunWithTimeout

Date: 2021-12-30
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Domain.Helpers
{
    public class TaskHelper
    {
        public static async Task<T> RunWithTimeout<T>(string taskName, Func<Task<T>> function, TimeSpan timeout)
        {
            using var cancelSource = new CancellationTokenSource();
            var task = function();
            var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cancelSource.Token));
            if (completedTask == task)
            {
                cancelSource.Cancel();
                return await task;  // Very important in order to propagate exceptions
            }
            else
            {
                throw new TimeoutException($"The operation '{taskName}' has timed out.");
            }
        }
    }
}
58640cookie-checkC# RunWithTimeout