Is it good to check the status, then block, and then re-check the condition

Possible duplicate:
Double check blocking in .net

EDIT: many changes to clarify this question not about singleton

I find myself writing code as follows:

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

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

+1
c # locking double-checked-locking
Feb 18 2018-11-18T00:
source share
2 answers

This is called a "double checked lock."

You need a memory fence to make it correct.

See Wikipedia article on double lock checking in .NET

+4
Feb 18 2018-11-18T00:
source share

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

+2
Feb 18 2018-11-18T00:
source share



All Articles