Beispiel #1
0
        public void Exchange_Twice_SecondFalse()
        {
            var subject = new AtomicBool();

            Assert.True(subject.Exchange(true));
            Assert.False(subject.Exchange(true));
        }
Beispiel #2
0
        public void Exchange_Concurrent()
        {
            int        accessedTimes = 0;
            var        gate          = new object();
            var        evt           = new ManualResetEvent(false);
            AtomicBool subject       = false;

            Task[] tasks = Enumerable.Repeat(
                Task.Run(
                    () =>
            {
                lock (gate)
                {
                    evt.WaitOne();
                }

                if (subject.Exchange(true))
                {
                    Interlocked.Increment(ref accessedTimes);
                }
            }),
                10)
                           .ToArray();

            evt.Set();

            Assert.True(Task.WaitAll(tasks, TimeSpan.FromSeconds(10)));
            Assert.Equal(1, accessedTimes);
        }