Asynchronously wait for Task to complete with timeout

后端 未结 16 1948
天命终不由人
天命终不由人 2020-11-21 17:49

I want to wait for a Task to complete with some special rules: If it hasn\'t completed after X milliseconds, I want to display a message to the user. And

16条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 18:20

    Using Stephen Cleary's excellent AsyncEx library, you can do:

    TimeSpan timeout = TimeSpan.FromSeconds(10);
    
    using (var cts = new CancellationTokenSource(timeout))
    {
        await myTask.WaitAsync(cts.Token);
    }
    

    TaskCanceledException will be thrown in the event of a timeout.

提交回复
热议问题