Async Task.WhenAll with timeout

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

    What you describe seems like a very common demand however I could not find anywhere an example of this. And I searched a lot... I finally created the following:

    TimeSpan timeout = TimeSpan.FromSeconds(5.0);
    
    Task[] tasksOfTasks =
    {
        Task.WhenAny(SomeTaskAsync("a"), Task.Delay(timeout)),
        Task.WhenAny(SomeTaskAsync("b"), Task.Delay(timeout)),
        Task.WhenAny(SomeTaskAsync("c"), Task.Delay(timeout))
    };
    
    Task[] completedTasks = await Task.WhenAll(tasksOfTasks);
    
    List = completedTasks.OfType>().Select(task => task.Result).ToList();
    

    I assume here a method SomeTaskAsync that returns Task.

    From the members of completedTasks, only tasks of type MyResult are our own tasks that managed to beat the clock. Task.Delay returns a different type. This requires some compromise on typing, but still works beautifully and quite simple.

    (The array can of course be built dynamically using a query + ToArray).

    • Note that this implementation does not require SomeTaskAsync to receive a cancellation token.

提交回复
热议问题