예제 #1
0
 public void TearDown()
 {
     ReadyToLockEvent.Dispose();
     LockAcquiredEvent.Dispose();
     ReadyToUnlockEvent.Dispose();
     LockReleasedEvent.Dispose();
 }
예제 #2
0
        public void TestLockAndRelease()
        {
            //-- Arrange

            DeriveClassFrom <AncestorRepository.StatementTester>()
            .DefaultConstructor()
            .Method <int, int>(cls => cls.DoTest).Implement((m, input) => {
                var syncRoot      = m.Local(initialValue: Static.Prop(() => SyncRoot));
                var readyToLock   = m.Local(initialValue: Static.Prop(() => ReadyToLockEvent));
                var lockAcquired  = m.Local(initialValue: Static.Prop(() => LockAcquiredEvent));
                var readyToUnlock = m.Local(initialValue: Static.Prop(() => ReadyToUnlockEvent));
                var lockReleased  = m.Local(initialValue: Static.Prop(() => LockReleasedEvent));

                m.If(!readyToLock.Func <int, bool>(x => x.WaitOne, m.Const(1000)))
                .Then(() => m.Throw <Exception>("readyToLock wait failed"));

                m.Lock(syncRoot, 100).Do(() => {
                    lockAcquired.Func <bool>(x => x.Set);

                    m.If(!readyToUnlock.Func <int, bool>(x => x.WaitOne, m.Const(1000)))
                    .Then(() => m.Throw <Exception>("readyToUnlock wait failed"));
                });

                lockReleased.Func <bool>(x => x.Set);
            });

            //-- Act

            var tester     = CreateClassInstanceAs <AncestorRepository.StatementTester>().UsingDefaultConstructor();
            var testerTask = Task.Factory.StartNew(() => {
                tester.DoTest(0);
            });

            //-- Assert

            ReadyToLockEvent.Set();

            if (!LockAcquiredEvent.WaitOne(1000))
            {
                Assert.Fail("LockAcquiredEvent wait failed.");
            }

            if (Monitor.TryEnter(SyncRoot))
            {
                Assert.Fail("SyncRoot must have been locked!");
            }

            ReadyToUnlockEvent.Set();

            if (!LockReleasedEvent.WaitOne(1000))
            {
                Assert.Fail("LockReleasedEvent wait failed.");
            }

            if (!Monitor.TryEnter(SyncRoot))
            {
                Assert.Fail("SyncRoot must have been released!");
            }

            if (!testerTask.Wait(1000))
            {
                Assert.Fail("Tester task is stuck");
            }
        }