1

Possible Duplicate:
Double-checked locking in .net

EDIT: lots of edits to clarify this question is not about singleton

I find myself writing code like this:

    if(resourceOnDiskNeedsUpdating)
    {
        lock(lockObject)
        {
            if(resourceOnDiskNeedsUpdating) // has a previous thread already done this?
                UpdateResourceOnDisk();
        }
    }
    return LoadResourceFromDisk();

UpdateResource() is a slow operation. Does this pattern make sense?
Are there better alternatives?

Community
  • 1
  • 1
Myster
  • 17,704
  • 13
  • 64
  • 93
  • in my case the Update resource is writing a file on disk, if that makes any difference. – Myster Feb 18 '11 at 00:58
  • I've made my question NOT about singletons, is it still a duplicate? should I try re-open it ? :-} – Myster Feb 18 '11 at 01:50
  • Yes, it's still a duplicate. The other question also was about DCL in general, most of the answers gave examples using singletons, because that's where DCL commonly appears, but there's no difference in scope between the questions. – Ben Voigt Feb 18 '11 at 01:59

2 Answers2

4

This called "double-checked locking".

You need a memory fence to make it correct.

See Wikipedia's article on double checked locking in .NET

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
2

An alternative I use would be to just use the 'volatile' keyword. http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx

  • Well, given your edit - make the variable 'resourceNeedsUpdating' volatile and do away with the secondary check in the lock. Add a variable indicating whether or not you're in the process of updating and check it before checking resourceNeedsUpdating / set it before/after calling UpdateResource, or unset resourceNeedsUpdating before calling UpdateResource. – Jeremy Sylvis Feb 18 '11 at 01:42