How to stop the Console.Readline()?

40 views Asked by At

I have a code, that calls Console.Readline and after 5 seconds ,if I won't get answer, I want stop him. How can I do this?

How I tried to do it:

CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
            CancellationToken token = cancelTokenSource.Token;
                Task task = new(() =>
                {
                    try
                    {
                        timer.Interval = 5000;
                        timer.Start();
                        timer.Elapsed += ((o, e) =>
                        {
                            cancelTokenSource.Cancel();
                            token.ThrowIfCancellationRequested();
                        });
                        Console.Write("Select need floor: ");

                        int needFloor = Convert.ToInt32(Console.ReadLine());
                        timer.Stop();
                        _elevator.Requests.Insert(0, needFloor);
                        _elevator.CloseDoor();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Not answer");
                    }
                    finally 
                    {
                        cancelTokenSource.Dispose();
                    }
                }, token);
            task.Start();
            task.Wait();
0

There are 0 answers