Async Task.WhenAll with timeout

后端 未结 11 2128
梦谈多话
梦谈多话 2020-11-29 04:33

Is there a way in the new async dotnet 4.5 library to set a timeout on the Task.WhenAll method. I want to fetch several sources and stop after say 5 seconds and

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 05:02

    In addition to timeout, I also check the cancellation which is useful if you are building a web app.

    public static async Task WhenAll(
        IEnumerable tasks, 
        int millisecondsTimeOut,
        CancellationToken cancellationToken)
    {
        using(Task timeoutTask = Task.Delay(millisecondsTimeOut))
        using(Task cancellationMonitorTask = Task.Delay(-1, cancellationToken))
        {
            Task completedTask = await Task.WhenAny(
                Task.WhenAll(tasks), 
                timeoutTask, 
                cancellationMonitorTask
            );
    
            if (completedTask == timeoutTask)
            {
                throw new TimeoutException();
            }
            if (completedTask == cancellationMonitorTask)
            {
                throw new OperationCanceledException();
            }
            await completedTask;
        }
    }
    

提交回复
热议问题