I rarely use single dots, in which case this is appropriate. When I tried to investigate the best implementation, I came across this bit of code that made me believe that I misunderstood how brackets encapsulate a "region".
public sealed class Singleton { private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { lock (padlock) { if (instance == null) { instance = new Singleton(); } return instance; } } } }
I am confused what happens when I try to access the "Instance". Say I'm working on single-user logging (my useful app for singlet), and it has a method called “WriteLine (line string)”
When i call:
Singleton.Instance.WriteLine("Hello!");
It supports locking during the execution of the entire WriteLine? Method.
What if I assign an instance to an external variable, for example:
Singleton Console = Singleton.Instance;
There is now a permanent link to a singleton outside of a singleton. Is Console.WriteLine("Hello!") Also completely thread safe, such as Singleton.Instance.WriteLine("Hello!") ?
In any case, I'm just confused how this makes a singleton thread safe and whether it is only thread safe when the property is explicitly available. I thought that Singlton.Instance.WriteLine("...") first pull out the instance, leaving the lock area, and then write WriteLine to the returned instance, so it would write after the lock was released.
Any help in resolving my misunderstanding of how these features will be rated.
source share