There is such a construction

Thread waitEnter = new Thread(() => { for (int i = 0; i < 5000; i++) { DrawField(); ruleSet.Tick(); } }); waitEnter.Start(); cki = Console.ReadKey(); if (cki.Key == ConsoleKey.Backspace) waitEnter.Abort(); 

In the last line I wanted to call Sleep, but it is not in the inaliens. I want the stream (application) to stop when I press the button, and when I press it again, it resumes.

    2 answers 2

    A safer method than Suspend / Resume, which can leave the data inconsistent, is to use an event or semaphore:

     var suspend = new ManualResetEvent(true); Thread waitEnter = new Thread(() => { for (int i = 0; i < 5000; i++) { // если событие не в сигнальном состоянии // поток приостановится здесь suspend.WaitOne(Timeout.Infinite); DrawField(); ruleSet.Tick(); } }); waitEnter.Start(); bool working = true; while (true) { var cki = Console.ReadKey(); if (cki.Key == ConsoleKey.Backspace) waitEnter.Abort(); if (cki.Key == ConsoleKey.Spacebar) { if (working) { suspend.Reset(); // приостановка на следующей итерации цикла } else { suspend.Set(); // возобновление } working ^= true; } } 
    • 2
      If it Thread.Abort to that, then Thread.Abort should not be used :) - kmv
    • used to put an approximate code - cruim
    • @kvm thanks for the decision - cruim
    • one
      Only it is still ManualResetEventSlim use ManualResetEventSlim - it will not do at least "idle" system calls. - Pavel Mayorov
    • +1 but working ^= true; completely unreadable. Better, in theory, working = !working; . - VladD

    You probably needed Suspend . And for renewal - Resume .

    Only be careful with these methods - your case (manual suspension / resumption by the user) is probably the only time when these methods are relevant. Do not use them for other purposes (for example, to synchronize threads).