1

please is there a way, how to close ReadKey task? I'm using this code in my console application:

            Task _task = Task.Factory.StartNew(() => Console.ReadKey());
            bool result = Task.WaitAny(new Task[] { _task }, TimeSpan.FromSeconds(5)) == 0
                ? true : false;

            if (result)
            {
                ....    
            }
            else
            {
                .....
                //Close ReadKey??
            }

And after using this code I need to use readkey again, but there is still runing the previous one. Any idea how to close first one, when "result" is false.

Blaato
  • 129
  • 10
  • have you tried passing a cancellation token when creating the task you want to cancel, then cancelling it? – rmjoia Oct 19 '17 at 12:18
  • Yes, but after cancel, there is still readkey running. But maybe I'm using it in a bad way. I dont have many experience with that. – Blaato Oct 19 '17 at 12:24
  • That's not possible. You must poll with KeyAvailable so you can be sure that ReadKey does not block. Also test for cancellation while you loop so you know when to break. And be sure to, say, Thread.Sleep(15) so you won't burn 100% core. – Hans Passant Oct 19 '17 at 12:25
  • Thank you for tyour respond, but like i said, I dont have many experience with that. Can I ask you for some example, please? – Blaato Oct 19 '17 at 12:28
  • cancelling is not enough, you have to wait for the result, and the cancelling will return a `TaskCancelledException` that you need to handle, at the very least, observe, then the task will be with the status `Completed`. I would recommend the reading of this resource: [Async in C# 5.0](http://shop.oreilly.com/product/0636920026532.do). – rmjoia Oct 19 '17 at 12:44
  • The problem here is that inside the Task `Console.ReadKey()` is blocking and does not accept a `CancellationToken` so you cannot really cancel that task before a key has actually been pressed – Peter Bons Oct 19 '17 at 13:20

0 Answers0