Note that there are some explanatory texts on larger screens.

plurals
  1. POIs Thread.Sleep the proper way to implement my own Timer in C#?
    primarykey
    data
    text
    <p>I am aware that System.Threading.Timer exists, but I already have a Thread. This thread is supposed to stay alive all the time, but only execute every X seconds. The test implementation looks like this:</p> <pre><code>public class MailClass { private Action&lt;string&gt; LoggerAction; private bool _exit; public MailClass(Action&lt;string&gt; loggerAction) { LoggerAction = loggerAction; } public void Run() { LoggerAction("Run called"); _exit = false; while(!_exit) { Thread.Sleep(TimeSpan.FromSeconds(300)); LoggerAction("Waking up"); } LoggerAction("Run ended"); } public void Stop() { LoggerAction("Stop called"); _exit = true; } } </code></pre> <p>The Run method executes, then sleeps for 5 Minutes, then executes again. So it's basically a timer that fires every 5 Minutes + the time it takes to execute the action. (and yes, I should cache the TimeSpan instead of re-creating it over and over)</p> <p>Is this the proper way to do it? (In the real app, the Run action checks a Web Service, so I have no way to signal my Thread to wake up earlier)</p> <p>Or should I use some other concept to have the thread? One problem I see is the implementation of Stop. The Run Thread runs a loop that checks a bool every time, but if I call Stop() I have to wait until the Sleep Interval is over, which is inconvenient.</p> <p>Thread.Abort would be harsh, so I guess Thread.Interrupt would work somehow? The Stop() Method should allow Run to finish it's current iteration, so no hard abort. AutoResetEvent looks a bit like what I could need, but I don't fully understand what it does.</p> <p><strong>Edit:</strong> One way I would see this possible is to add a Timer (so a separate thread) and then have Run() end not with Thread.Sleep but with some "Wait until some object changes". I would then change that object either from the second Thread (when the 5 minutes expire) or from the Stop action. But that seems excessive? Essentially, Run needs to react to two conditions: 5 Minutes expire <em>or</em> some external signal (like the change of the _exit flag). Something tells me there should be something built-in, but maybe having another Timer Thread solely focused on sending a signal every 5 minutes is the way to go?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload