K
K
kill942015-10-07 00:01:02
C++ / C#
kill94, 2015-10-07 00:01:02

How to implement a function until a key is pressed?

How to implement until the key is pressed to execute the function. When pressed, finish execution, and after processing the keypress event, perform the same function.
Here's something like this.

do
            {
                do
                {
                    //функция 
                } while (!Console.KeyAvailable);
          
                //обработка события нажатия на клавишу
            } while (Console.ReadKey().Key != ConsoleKey.Escape);

But this is in the console, and I need to implement all this on the form

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
pupunussi, 2015-10-07
@kill94

Create a CancellationTokenSource and take its Token :

var source = new CancellationTokenSource();
var token = source.Token;

Create and run a task :
Task.Run(() =>
{
    do
    {

    }
    while (!token.IsCancellationRequested);
});

In the button we tell the task what to finish :
source.Cancel();

P
patch1, 2015-10-07
@patch1

keypress - link

A
AxisPod, 2015-10-07
@AxisPod

It's not easy to do this on a form. Read about threads and events. At a minimum, it will be necessary to make a background thread with the ability to interrupt, which will do everything that is needed, otherwise the UI will freeze and it will not lead to anything good.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question