public void Singleton_Should_Be_Thread_Safe() { int threadsCount = 10; EventWaitHandle threadsFinished = new EventWaitHandle(false, EventResetMode.AutoReset); MockSingleton[] singletons = new MockSingleton[threadsCount]; Thread[] threads = new Thread[threadsCount]; Barrier startBarrier = new Barrier(threadsCount); Barrier finishBarrier = new Barrier(threadsCount, (barrier) => threadsFinished.Set()); for (int i = 0; i < threadsCount; i++) { threads[i] = new Thread((idx) => { startBarrier.SignalAndWait(); // Wait for creating all other threads try { singletons[(int)idx] = Singleton <MockSingleton> .Instance; } catch { } finishBarrier.SignalAndWait(); // Wait for finishing all other threads }); threads[i].Start(i); } threadsFinished.WaitOne(); var inst = Singleton <MockSingleton> .Instance; inst.IntProperty++; Assert.IsTrue(singletons.All(x => x.IntProperty == inst.IntProperty), "Singleton<T> shoud inplement thread safe initialization"); }
public void CreateSingletonTest() { MockSingleton.CreateInstance(() => new MockSingleton { Id = 45 }); var m1 = MockSingleton.Instance; MockSingleton.Instance.Id = 5; Assert.Equal(m1, MockSingleton.Instance); Assert.NotEqual(45, m1.Id); }
public void Singleton_CRTP_Creates_The_Instance() { MockSingleton.InitSingleton(); Assert.NotNull(MockSingleton.Instance); MockSingleton.DestroySingleton(); }