Async Task.WhenAll with timeout

后端 未结 11 2113
梦谈多话
梦谈多话 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 04:45

    In addition to svick's answer, the following works for me when I have to wait for a couple of tasks to complete but have to process something else while I'm waiting:

    Task[] TasksToWaitFor = //Your tasks
    TimeSpan Timeout = TimeSpan.FromSeconds( 30 );
    
    while( true )
    {
        await Task.WhenAny( Task.WhenAll( TasksToWaitFor ), Task.Delay( Timeout ) );
        if( TasksToWaitFor.All( a => a.IsCompleted ) )
            break;
    
        //Do something else here
    }
    

提交回复
热议问题