Last week, for a Azure POC, we implemented something similar to the pattern shown in Part 1. One revision, that I asked to be made, was to surround the DateTime access code with a lock statement; I was worried that updating a DateTime struct would not be thread safe - i.e the thread querying the lastHeathyReport would be reading its value while the main thread was part way through modifying it. This could lead to the health check comparing against an incorrect or invalid DateTime and unnecessarily mark up the role as unhealthy. The code to perform the locking would look like:

    // Declaring the date time and our lock
    private DateTime lastThreadTest;

    private Object dateTimeLock = new Object();
    public override void Start()
    {
        // This is a sample worker implementation. Replace with your logic.
        RoleManager.WriteToLog("Information", "Worker Process entry point called");

        while (true)
        {
            // Updating the date time in the main loop
            lock (dateTimeLock)
            {
                lastThreadTest = DateTime.Now;
            }
            // Do some work
        }
    }
    public override RoleStatus GetHealthStatus()
    {
        // Querying the date time
        lock (dateTimeLock)
        {
            if (lastHealthyReport.AddSeconds(30) < DateTime.Now)
            {
                return RoleStatus.Unhealthy;
            }
            return RoleStatus.Healthy;
        }
    }

Having researched whether the lock is need, I can categorically state that the answer is ... "it depends". The DateTime struct in the .Net framework uses an unsigned 64 bit integer to store its value. Assignment of a 64 value on a 32 bit machine is not atomic - it takes 2 machine instructions to write 64 bits, however on a 64 bit machine it is atomic. As windows Azure instances are 64 bit machines, the question of whether to lock is probably going to come down to what your dev machine is. However, taking out an uncontested lock in .Net is a very inexpensive operation, so I think, my recommendation would be to put the lock in.

If you are interested, the specs of an Azure machine for the Tech Preview are as follows - this is the virtual machine, not the actual physical servers!

  • Platform: 64-bit Windows Server 2008
  • CPU: 1.5-1.7 GHz x64 equivalent
  • Memory: 1.7 GB
  • Network: 100 Mbps
  • Transient local storage: 250 GB

And for more information on thread safety and torn reads, see Joe Duffy's posting.

Neil