Asynchronously wait for Task to complete with timeout

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

    Another way of solving this problem is using Reactive Extensions:

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

    Test up above using below code in your unit test, it works for me

    TestScheduler scheduler = new TestScheduler();
    Task task = Task.Run(() =>
                    {
                        int i = 0;
                        while (i < 5)
                        {
                            Console.WriteLine(i);
                            i++;
                            Thread.Sleep(1000);
                        }
                    })
                    .TimeoutAfter(TimeSpan.FromSeconds(5), scheduler)
                    .ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
    
    scheduler.AdvanceBy(TimeSpan.FromSeconds(6).Ticks);
    

    You may need the following namespace:

    using System.Threading.Tasks;
    using System.Reactive.Subjects;
    using System.Reactive.Linq;
    using System.Reactive.Threading.Tasks;
    using Microsoft.Reactive.Testing;
    using System.Threading;
    using System.Reactive.Concurrency;
    

提交回复
热议问题