There's plenty of examples of people saying to use a Timer
instead of Thread.Sleep(...)
in an Azure Worker Role
. No probs with that.
What I'm struggling to understand is how to code this.
Currently, I have the following (pseduo code)
_timer.Elapsed += (sender, args) => DoWork();
public override void Run()
{
while(true)
{
DoWork();
}
}
public void DoWork()
{
try
{
_timer.Stop();
// Now - do stuff ....
}
catch(....) { ... }
_timer.Start()
}
And what happens, is that the code enters the DoWork()
method once and DoesStuff(tm)
.. fine .. starts the timer (say .. with a 30 second interval) and then exits that method.
Then, it returns back to the main Run()
method .. which is in that loop. So it immediately comes back around and enters the DoWork()
method again .. instead of waiting for the timer to fire it off.
So I'm not sure how to replace any Thread.Sleep(...)
with Timers.
Any clues?
Clarification
I do not want to exit the Run()
method :) I'm very happy to keep looping forever. What I'm stuck with, is replacing the standard Thread.Sleep(...)
call (which blocks the thread) and replace that with a Timer
, which most people suggest.
Update
Please do not link or suggest that I should use cancelSource.Token.WaitHandle.WaitOne();
as a solution. That is not what I'm trying to achieve here. Please note the post title!
Thread.Sleep(..)
because it's NotGood(tm)? – HardnettThread.Sleep(..)
to 'pause' the worker (for a while). Instead, I want to use a Timer. – HardnettancelSource.Token.WaitHandle.WaitOne(); solution, that's actually not what I'm after :( I'm after a solution that leverage's
Timer.Start()` andTimer.Stop()
(as mentioned in the Subject and Body of the message). – Hardnett