Most beautifully, this is done through the CancellationToken mechanism. This mechanism is specifically designed to transmit stop and cancel messages between threads:
void run(object p) { var ct = (CancellationToken)p; do { // что-то делаем doAnything(p); } while (!ct.IsCancellationRequested && !ct.WaitHandle.WaitOne(60000)); }
Here I use event wait as an interrupted alternative to Thread.Sleep . If waiting is successful, it means that the flow should be stopped. If unsuccessful (timeout waiting) - then you can continue to work.
Before waiting, I check IsCancellationRequested to not create a kernel event when this is not required.
Creating such a stream:
using (var cts = new CancellationTokenSource()) { new Thread(run).Start(cts.Token); ... cts.Cancel(); }
Also, instead of a stream, you can use a task ( Task.Run ). In this case, it is better to use Task.Delay , this will make it possible to do without the kernel objects:
async Task run(CancellationToken ct) { do { // что-то делаем doAnything(p); await Task.Delay(60000, ct); } while (!ct.IsCancellationRequested); } Task.Run(() => run(cts.Token));
A bonus to using CancellationToken is the ability to send ct further to doAnything - so you can finely choose at what points the interruption of processing is acceptable.
If you use the asynchronous version, then almost all the asynchronous functions of the standard library can also accept CancellationToken , which allows you to safely interrupt any long operation if you wish.
In older runtimes where the CancellationToken mechanism is not present, ManualResetEvent can be used for the same purpose. The principle is the same - instead of calling Thread.Sleep wait on the event and check the result.