Async Task.WhenAll with timeout

后端 未结 11 2039
梦谈多话
梦谈多话 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:09

    I think a clearer, more robust option that also does exception handling right would be to use Task.WhenAny on each task together with a timeout task, go through all the completed tasks and filter out the timeout ones, and use await Task.WhenAll() instead of Task.Result to gather all the results.

    Here's a complete working solution:

    static async Task WhenAll(IEnumerable> tasks, TimeSpan timeout)
    {
        var timeoutTask = Task.Delay(timeout).ContinueWith(_ => default(TResult));
        var completedTasks = 
            (await Task.WhenAll(tasks.Select(task => Task.WhenAny(task, timeoutTask)))).
            Where(task => task != timeoutTask);
        return await Task.WhenAll(completedTasks);
    }
    

提交回复
热议问题