I have a problem in choosing the right method to accomplish my goal.
I’m working on Algorithms teaching system, I’m using C#. I need to divide my algorithm into steps, each step will contain a recursion.
I have to stop execution after each step, user can then move to the next step(next recursion) using a button in my GUI.
After searching, threads was the right choice, but I found several methods:
-
(Thread.sleep/interrupt): didn’t work, my GUI freezed !!
-
(Suspend/Resume): I’ve read that it’s a bad idea to use.
-
(Waithandles): still reading about them.
-
(Monitor wait/resume).
I don’t have much time to try and read all previous methods, please help me in choosing the best method that fits my system.Any suggestions are extremal welcomed.
Fundamentally, this question is not really about recursion or multi-threading, it is simply this:
Implementing your own threading model is not the way to go here, especially if you are just starting to learn about multi-threaded/async operations. The .NET Framework already has a component for what you want to do: BackgroundWorker, which works in both Winforms and WPF (and almost any other architecture).
It is very, very easy to do what you want using the
BackgroundWorker. I’ll assume Winforms for this example but this is just as easy in WPF.You obviously also have to wire up the
DoWorkandRunWorkerCompletedevents, and make sure to setWorkerSupportsCancellationtotrueon theBackgroundWorker. After that, you run the operation with:And cancel with:
The only wrinkle here is that you say you want to pause (not stop) execution after each “step”. I would probably do this using an
AutoResetEvent, which is a type of event that resets its signaled (“ready”) state every time a wait succeeds. Again, it’s only a few lines of code to integrate:There’s one thing that might warrant additional explanation here and that is the cancel method, which first cancels and then sets the
continueEvent. It’s necessary to do this because if the worker is still waiting for the event, it won’t actually get to the cancellation stage, so when you cancel, you need to allow the worker to continue. You also need to set thecontinueEventwhen you start the worker if you want it to execute the first step without requiring the user to hit “continue.”