c# - Is it ok to use following 'thread safe double checked lazy initilalization' pattern? -
c# - Is it ok to use following 'thread safe double checked lazy initilalization' pattern? -
framework: .net 4.5
i using below sample code pattern initialize variables in thread safe manner. have been reading articles explains 'double checked locking has been broken in platforms http://www.cs.umd.edu/~pugh/java/memorymodel/doublecheckedlocking.html ' looks ok me using .net 4.5.
recommendation per comments
recommendation utilize lazy , allow .net framework heavy lifting of handling thread safety , memory models based on platforms:) : http://msdn.microsoft.com/en-us/library/dd642331.aspx
update
it appears eric lippert has been recommending not utilize pattern @ (now confused :() name pattern? (answer: lazy initialization double-checked locking) c# manual lock/unlock
update 2
following excerpt "like techniques remove read locks, code in figure 7 (similar code have) relies on strong write ordering. example, code wrong in ecma memory model unless myvalue made volatile because writes initialize lazyinitclass instance might delayed until after write myvalue, allowing client of getvalue read uninitialized state. in .net framework 2.0 model, code works without volatile declarations." http://msdn.microsoft.com/en-us/magazine/cc163715.aspx
and not using 'volatile' many examples showed in different code snippets. assuming ok (reference: the need volatile modifier in double checked locking in .net )
** psudeo code - explains version using - built on top of .net 4.5 **
static private object s_syncobject = new object(); private static string s_lazyinitializedvariable = null; //is necessar create backing varible volatie? //private static volatile string s_lazyinitializedvariable = null; private static string lazyinitializedvariable { { if(string.isnullorwhitespace(s_lazyinitializedvariable)) { lock(s_syncobject) { if (string.isnullorwhitespace(s_lazyinitializedvariable)) { /* * lazy initialization code */ s_lazyinitializedvariable = "initialized"; } } } homecoming s_lazyinitializedvariable; } }
can 1 please confirm same? below assumptions using .net 4.5
i assuming ok utilize below code , ignore volatile statement? please ratify if assumptions ok.note: noticed can create utilize of 'lazy' introduced in .net 4.0. of live way doing guess, have seen implementation of lazy using ilspy, , looks doing relatively more stuff simple tasks mine...
best regards.
static initialization in clr guaranteed thread-safe. either of next fine thread-safe initialization:
static string s_lazyinitializedvariable = "initialized";
if want lazy, utilize lazy class:
static lazy<string> s_lazyinitializedvariable = new lazy<string>(() => "initialized");
c# .net multithreading
Comments
Post a Comment