How to pause the background thread, and then continue at the click of a button?

I have a Windows form and a class with two simple methods that work in a recursively non-deterministic way (which means that it is not known which recursion will be called, and both can cause the other) ... Now there are some points during this recursion, on which I want to pause, and wait for the user to click the "Next Step" button. Only after pressing a button if recursive functions continue. The class runs in a separate thread, so it does not block the user interface.

During this pause, the form simply extracts the value from the class and displays it in the list. Then, after pressing the button, the recursion continues until the next pause (). I need this so that the user can see what happens in the recursion step by step. Also I need to be able to put Pause () anywhere in the recursive method (even several times) without causing any side effects ...

The only way that comes to my mind is to call the Pause () method, in which the loop checks for some blocked flag and then sleeps for a while (the button then sets the flag), but I had some unpleasant impressions from Thread.Sleep () in Windows Forms (UI lock), so I'm considering other options.

Is there any clean way to do this?

+3
source share
3 answers

Use ManualResetEventthat is initialized to true, so it starts to install. In a famous place in one way or another (or both), wait for the event. In most cases, the event will be set so that the background thread continues immediately. However, when the user clicks the “Pause” button, reset the event, causing the background thread to block the next time it reaches the event. When the user clicks the Resume button, set the event to resume the background thread.

There is no reason why the user interface thread should be blocked in this scenario.

+6

AutoResetEvent.

.WaitOne , , .Set , .

+2

Mutex . Mutex, , .

GUI Mutex, , , .

, , , Mutex, .

" " , .

// this object has to be visible to both threads
System.Threading.Mutex mtx = new Mutex();

// worker thread does this wherever it ok for it to pause
mtx.WaitOne();
mtx.ReleaseMutex();

// main thread does this to pause the worker
Mtx.WaitOne();

// main thread does this this to unpause it.
mtx.ReleaseMutex();
+1

Source: https://habr.com/ru/post/1726400/


All Articles