public void TestSingleton3() { FiveSecondSingleton s1, s2, s3; s1 = FiveSecondSingleton.GetInstance(); Thread.Sleep(TimeSpan.FromSeconds(4)); s2 = FiveSecondSingleton.GetInstance(); Thread.Sleep(TimeSpan.FromSeconds(2)); s3 = FiveSecondSingleton.GetInstance(); Assert.AreSame(s1, s2); Assert.AreNotSame(s1, s3); Assert.AreNotSame(s2, s3); }
public static FiveSecondSingleton GetInstance() { lock (lockObj) { if (instance == null) { instance = new FiveSecondSingleton(); timer = DateTime.Now; } else { TimeSpan interval = DateTime.Now - timer; if (interval.Seconds >= 5) { instance = new FiveSecondSingleton(); timer = DateTime.Now; } } } return(instance); }