"George" <no*****@comcast.netwrote in message
news:u7**************@TK2MSFTNGP06.phx.gbl...
I am trying to implement postponed initialization (object is not
initialize till requested).
public class clsStore
{
volatile List<clsPictureGroup_lstPictureGroups = null;
public List<clsPictureGroupPictureGroups
{
get
{
if (_lstPictureGroups == null)
{
lock (this)
{
if (_lstPictureGroups == null)
_lstPictureGroups = LoadPictureGroup();
}
}
return _lstPictureGroups;
}
}
}
Obviously this code suppose to run in multithreaded enviroment in ASP.NET.
Anyone sees any problem in this code?
As far as i can see there is no 'race' condition here and code is safe.
There are a few problems.
1) Best practice is to create a separate member to act as the lock variable:
private object _locker = new object()
2) The member need not be volatile - you are only going to change it while
it is locked, right?
3) You do not need to initialize it to null, as that is the default value.
This is not C or C++ - there is a specific default value for every type, so
there is no need to initialize something just to make sure you're not
accessing uninitialized data. There _is_ no uninitialized data.
The fourth is just a matter of style. Classes are not an unusual construct
in C#. In fact, they are the norm. It is really very redundant to prefix
every class with "cls". Similarly, do you really want to prefix all of your
lists with "lst"? You will learn more from hovering the mouse over the
member in the editor than by seeing "lst", which could mean any sort of list
(unless you restrict "lst" to be only List<T>).
--
John Saunders | MVP - Connected System Developer