public void TestWithoutParaller() { var a = LockSingleton.getInstance(); var b = LockSingleton.getInstance(); Assert.IsTrue(object.ReferenceEquals(a, b)); }
public void GetInstancesWithParaller() { Parallel.For(0, 100000, task => { LockSingleton.getInstance(); }); Assert.AreEqual(1, LockSingleton.counter); }
public void TestLockSingletonWithParaller() { LockSingleton a = null; LockSingleton b = null; LockSingleton c = null; Parallel.Invoke( () => { c = LockSingleton.getInstance(); }, () => { b = LockSingleton.getInstance(); }, () => { a = LockSingleton.getInstance(); }, () => { c = LockSingleton.getInstance(); }, () => { c = LockSingleton.getInstance(); } ); Assert.IsTrue(object.ReferenceEquals(a, b)); Assert.AreEqual(1, LockSingleton.counter); }
/// <summary> /// 双重锁定Sigleton /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_DoubLockSigleton_Click(object sender, System.EventArgs e) { LockSingleton s1 = LockSingleton.Instance; LockSingleton s2 = LockSingleton.Instance; string strResult = ""; if (s1.Equals(s2)) { strResult = "[LockSingleton]the same instance"; } else { strResult = "[LockSingleton]the defferent instance"; } UpdateResult(strResult); }
public void ShouldTheSingletonDesignPatternUsingLockCreatingASingleInstance() { LockSingleton firstInstance = null; LockSingleton SecondInstance = null; Parallel.Invoke( () => firstInstance = LockSingleton.Instance, () => SecondInstance = LockSingleton.Instance); firstInstance.Should().Be(SecondInstance); LockSingleton.Counter.Should().Be(1); // The point that you need to remember is Lock is the best option to handle the singleton instance // Using locks we can synchronize the method. So that only one thread can access it at any given point of time. // We lock the shared resource and then checks whether the instance is created or not. // If the instance is already created then we simply return that instance else we will create the instance and then return that instance. // IMPORTANT: // The implementation using lock solves the multithreading issue. But the problem is that it is slow down your application as only one // thread can access the Instance property at any given point of time. We can overcome this problem by using the Double-checked locking mechanism. }