Azure Worker Role Threading

Working with multiple threads in Windows Azure can be tough, but there is an easy change you can adopt to make your life easier. If you have been working with Azure worker roles, or have just started, you are probably familiar with the following code.

while(Run)
{
  // ... 
  Thread.Sleep(10000);
}

OnStop() 
{
  Run = false;
}

This will get you up and running and most people probably find it “okay” for a while. But, after some time you may start to run into trouble - and there are a lot of vectors to get you there. {“ “The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.” “}
Its important to really understand what is going on when execute Thread.Sleep. According to documentation…

Why is this bad?

Well, when you use Thread.Sleep within the primary executing thread of the Azure Worker role, you are essentially freezing your application. This really becomes a problem if your thread is holding a resource that needs to be accessed from outside of the thread. You most likely won’t even stumble on this until you need to do multiple threads within a single Azure worker role.

So how do you do it right?

We use the ManualResetEvent which is a primitive in .NET.

ManualResetEvent resetEvent = new ManualResetEvent(false);
while(Run)
{
  // ...
  resetEvent.WaitOne(10000);
}

Pretty straight forward. But what does this do? Well, there is a fantastic Stack Overflow question that has a wealth of info for that. Needless to say, it is going to save you headaches in the future when all you need to do is wait a few seconds to check something again.