Asynchronously wait for Task to complete with timeout

后端 未结 16 2035
天命终不由人
天命终不由人 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:29

    A generic version of @Kevan's answer above, using Reactive Extensions.

    public static Task TimeoutAfter(this Task task, TimeSpan timeout, IScheduler scheduler)
    {
        return task.ToObservable().Timeout(timeout, scheduler).ToTask();
    }
    

    With optional Scheduler:

    public static Task TimeoutAfter(this Task task, TimeSpan timeout, Scheduler scheduler = null)
    {
        return scheduler is null 
           ? task.ToObservable().Timeout(timeout).ToTask() 
           : task.ToObservable().Timeout(timeout, scheduler).ToTask();
    }
    

    BTW: When a Timeout happens, a timeout exception will be thrown

提交回复
热议问题