Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Background thread pause and then continue on button click?

I have a Windows Form and a class with two simple methods that run recursively in a nondeterministic way (meaning that it's unknown which recursion will be called, both can call the other)... Now, there are some points during that recursion at which I want to pause the execution and wait for a user to click on the "Next Step" button. Only after the button is pressed should the recursive functions continue. The class runs on a separate thread so it doesn't block the UI.

During that pause, the Form would simply retrieve the value from the class and display it in a listbox. Then after the button is pressed, the recursion continues until the next Pause(). I need this so the user can see what is happening in the recursion step by step. Also I need to be able to put Pause() anywhere in the recursive method (even multiple times) without causing any side-effects...

The only way that comes to my mind is to call Pause() method in which a loop checks some locked flag and then sleeps for some time (the button would then set the flag), but I had some bad experiences with Thread.Sleep() in Windows Forms (locking the UI) so I am looking at another options.

Is there any clean way to do this?

like image 928
Kornelije Petak Avatar asked Dec 30 '22 07:12

Kornelije Petak


2 Answers

Use a ManualResetEvent that is initialized to true, so it begins set. At a well-known place in one method or the other (or both), wait for the event. Most of the time, the event will be set so the background thread will continue immediately. When the user clicks Pause, however, reset the event, causing the background thread to block the next time it reaches the event. When the user next clicks "Resume", set the event, allowing the background thread to continue again.

There's no reason that the UI thread should ever block in this scenario.

like image 117
JSBձոգչ Avatar answered Feb 06 '23 00:02

JSBձոգչ


Use a AutoResetEvent object.

Call the .WaitOne method on it from your thread to pause it, and call the .Set method on it from your button to unpause it.

like image 22
Lasse V. Karlsen Avatar answered Feb 05 '23 22:02

Lasse V. Karlsen