REnt12 REnt12 - 3 months ago 18
C# Question

How to pause a loop mid-iteration

I need to pause a loop mid-iteration (any point during a long series of commands in a while statement). While I understand how to use event handles to pause at the end of an iteration, I am unsure how to achieve a similar effect during the sequence of commands.

An example for clarity:

Thread 1 :

while (true)
{
// commands
}

Thread 2 :

Console.ReadLine();

//if 1 is pressed the first thread (Thread 1) must immediately pause.


Any help would be greatly appreciated. P.S I am a beginner so a detailed explanation would be invaluable.

Answer

I am unsure how to achieve a similar effect during the sequence of commands.

Put simply: you shouldn't. Unless you have knowledge of what code is doing at any point, you shouldn't try to interrupt it. Of course, if that code elects to invoke the same "While I understand how to use event handles to pause at the end of an iteration" logic in the middle of a flow, then fine - but that is for the running code to decide, not the controlling code. Pausing arbitrary code is a great way to break things, which is why Thread.Suspend has been deprecated.

But this is perfectly valid:

while (true) 
{
    ElectivePauseIfNeeded();
    // ... some commands
    ElectivePauseIfNeeded();
    // ... some more commands
}

The point here is that it is the loop that decides when it is safe to pause, not the outside code.

Comments