c# - How does a singleton property with a lock ensure thread safety? -


i use singletons, in case it's appropriate. while trying investigate best implementation thereof came across bit of code has left me believing improperly understand how brackets encapsulate "scope."

public sealed class singleton {     private static singleton instance = null;     private static readonly object padlock = new object();      singleton()     {     }      public static singleton instance     {                 {             lock (padlock)             {                 if (instance == null)                 {                     instance = new singleton();                 }                 return instance;             }         }     } }  

i'm confused happens when attempt access "instance." i'm working on logging singleton (my useful application singleton) , has method "writeline(string line)"

when call:

singleton.instance.writeline("hello!"); 

it maintains lock during execution of entire method of "writeline?"

what if assign instance external variable like:

singleton console = singleton.instance; 

now there's constant reference singleton outside of singleton. console.writeline("hello!") thread safe singleton.instance.writeline("hello!")?

anyway, i'm confused how makes singleton thread safe , whether or not it's thread safe when property explicitly accessed. thought singlton.instance.writeline("...") pull out instance first, thereby leaving scope of lock, , execute writeline on returned instance, therefore performing write after lock has been released.

any on clearing misunderstanding of how functions appreciated.

does singleton.instance.writeline("hello!"); maintain lock during execution of entire method of writeline?

no, lock guards creation of singleton. writeline executes unlocked (unless, of course, obtains own lock internally).

is console.writeline("hello!") thread safe singleton.instance.writeline("hello!")?

it equally safe or unsafe singleton.instance, because lock not maintained outside of instance's getter.

anyway, i'm confused how makes singleton thread safe

lock makes process of obtaining instance of singleton thread-safe. making methods of singleton thread-safe process not depend on whether object singleton or not. there no simple turn-key one-fits-all solution making thread-unsafe object behave in thread-safe way. address 1 method @ time.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -