User loginNavigation |
Thread-safe Singleton in C#This has two parts. Please read first part first and think and then read second part. 1 public class SingletonClass 2 { 3 private SingletonClass () { Constructor (); } 4 static SingletonClass instance; 5 public static SingletonClass Instance 6 { 7 get 8 { 9 lock (typeof (SingletonClass)) 10 { 11 if (instance == null) 12 instance = new SingletonClass (); 13 lock (instance) 14 { 15 return instance; 16 } 17 } 18 } 19 } 20 void Constructor () { } 21 } -------------------------------------------------------------------------------- + Second part: 1 public class SingletonClass 2 { 3 public static object Hey_IAmStillUsingThisInstance_Lock = new object (); 4 private SingletonClass () { Constructor (); } 5 static SingletonClass instance; 6 public static SingletonClass Instance 7 { 8 get 9 { 10 lock (typeof (SingletonClass)) 11 { 12 if (instance == null) 13 instance = new SingletonClass (); 14 lock (instance) 15 { 16 return instance; 17 } 18 } 19 } 20 } 21 void Constructor () { } 22 public void DoSomthing () { } 23 } 100 static void Main(string[] args) 101 { 102 lock (SingletonClass.Hey_IAmStillUsingThisInstance_Lock) 103 { 104 SingletonClass.Instance.DoSomthing (); 105 } 106 } This filth is shared memory. >:( By kaveh.shahbazian at 2007-08-22 10:51 | LtU Forum | previous forum topic | next forum topic | other blogs | 19884 reads
|
Browse archives
Active forum topics |
Recent comments
22 weeks 6 days ago
22 weeks 6 days ago
22 weeks 6 days ago
45 weeks 15 hours ago
49 weeks 2 days ago
50 weeks 6 days ago
50 weeks 6 days ago
1 year 1 week ago
1 year 6 weeks ago
1 year 6 weeks ago