Asynchronously wait for Task to complete with timeout

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

    What about something like this?

        const int x = 3000;
        const int y = 1000;
    
        static void Main(string[] args)
        {
            // Your scheduler
            TaskScheduler scheduler = TaskScheduler.Default;
    
            Task nonblockingTask = new Task(() =>
                {
                    CancellationTokenSource source = new CancellationTokenSource();
    
                    Task t1 = new Task(() =>
                        {
                            while (true)
                            {
                                // Do something
                                if (source.IsCancellationRequested)
                                    break;
                            }
                        }, source.Token);
    
                    t1.Start(scheduler);
    
                    // Wait for task 1
                    bool firstTimeout = t1.Wait(x);
    
                    if (!firstTimeout)
                    {
                        // If it hasn't finished at first timeout display message
                        Console.WriteLine("Message to user: the operation hasn't completed yet.");
    
                        bool secondTimeout = t1.Wait(y);
    
                        if (!secondTimeout)
                        {
                            source.Cancel();
                            Console.WriteLine("Operation stopped!");
                        }
                    }
                });
    
            nonblockingTask.Start();
            Console.WriteLine("Do whatever you want...");
            Console.ReadLine();
        }
    

    You can use the Task.Wait option without blocking main thread using another Task.

提交回复
热议问题