I can't figure out how to do this in a good way.
Basically, I have a program with two key tasks that contain loops that it runs over and over until the user clicks the stop button.
Pseudo code:
- Task A is started: a while loop that does work continuously
- Task B is started: a
System.Timers.Timer
that checks continuously for a specific condition - If Task B finds the condition to be true, it should temporarily stop Task A, and do a bunch of work
- Once Task B is done with that work it should allow Task A to start looping again, and go back to checking for the specific condition
This then all continues in perpetuity (until user clicks stop button and the program ends).
When I made the first iteration of the program I basically created two separate threads, and then just had bools in the loops that i used for cancellation. So, Task B just set the bool in Task A to be false and used a Thread.Join()
to wait until Task A had completely finished before it started doing its work. Once Task B was done, it created Task A on a completely new thread again. This seemed highly inefficient, as there is no reason I should really have to end the thread, when all I want to do is just halt it until Task B is done.
I have been reading up on async
ops through Task Parallel Library (async-await
), and thought I could perhaps use cancellation tokens instead of the bools, but it looks like once a task is cancelled with cancellation token the token cannot be reset and task cannot be restarted.
In any case, how would you build this?