示例#1
0
        public void DoubleCloseTest()
        {
            var target = new MyTarget();
            target.Initialize(null);
            target.Close();
            target.Close();

            // initialize and close were called once each
            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.CloseCount);
            Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
示例#2
0
        public void DoubleCloseTest()
        {
            var target = new MyTarget();

            target.Initialize(null);
            target.Close();
            target.Close();

            // initialize and close were called once each
            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.CloseCount);
            Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
示例#3
0
        public void WriteOnClosedTargetTest()
        {
            var target = new MyTarget();

            target.Initialize(null);
            target.Close();

            var exceptions = new List <Exception>();

            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            target.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));

            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.CloseCount);

            // write was not called
            Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);

            // but all callbacks were invoked with null values
            Assert.Equal(4, exceptions.Count);
            exceptions.ForEach(Assert.Null);
        }
示例#4
0
        public void CloseWithoutInitializeTest()
        {
            var target = new MyTarget();
            target.Close();

            // nothing was called
            Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
示例#5
0
        public void CloseWithoutInitializeTest()
        {
            var target = new MyTarget();

            target.Close();

            // nothing was called
            Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
示例#6
0
        public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents()
        {
            var myTarget = new MyTarget {
                FailCounter = 1
            };
            var myTarget2     = new MyTarget();
            var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2);
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = fallbackGroup,
                BufferSize    = 10,
            };

            InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup);

            const int totalEvents = 100;

            var continuationHit    = new bool[totalEvents];
            var lastException      = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                ex =>
            {
                lastException[eventNumber]      = ex;
                continuationThread[eventNumber] = Thread.CurrentThread;
                continuationHit[eventNumber]    = true;
            };

            using (new NoThrowNLogExceptions())
            {
                // write 9 events - they will all be buffered and no final continuation will be reached
                var eventCounter = 0;
                for (var i = 0; i < 9; ++i)
                {
                    targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
                }

                Assert.Equal(0, myTarget.WriteCount);

                // write one more event - everything will be flushed
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
                Assert.Equal(1, myTarget.WriteCount);
                Assert.Equal(10, myTarget2.WriteCount);

                targetWrapper.Close();
                myTarget.Close();
            }
        }
示例#7
0
        public void LockingTest()
        {
            var target = new MyTarget();

            target.Initialize(null);

            var mre = new ManualResetEvent(false);

            Exception backgroundThreadException = null;

            Thread t = new Thread(() =>
            {
                try
                {
                    target.BlockingOperation(1000);
                }
                catch (Exception ex)
                {
                    backgroundThreadException = ex;
                }
                finally
                {
                    mre.Set();
                }
            });


            target.Initialize(null);
            t.Start();
            Thread.Sleep(50);
            List <Exception> exceptions = new List <Exception>();

            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            target.WriteAsyncLogEvents(new[]
            {
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
            });
            target.Flush(exceptions.Add);
            target.Close();

            exceptions.ForEach(Assert.Null);

            mre.WaitOne();
            if (backgroundThreadException != null)
            {
                Assert.True(false, backgroundThreadException.ToString());
            }
        }
示例#8
0
        public void RetryingTargetWrapperBlockingCloseTest()
        {
            RetryingIntegrationTest(3, () =>
            {
                var target = new MyTarget()
                {
                    ThrowExceptions = 5,
                };
                var wrapper = new RetryingTargetWrapper()
                {
                    WrappedTarget          = target,
                    RetryCount             = 10,
                    RetryDelayMilliseconds = 5000,
                };
                var asyncWrapper = new AsyncTargetWrapper(wrapper)
                {
                    TimeToSleepBetweenBatches = 1
                };

                asyncWrapper.Initialize(null);
                wrapper.Initialize(null);
                target.Initialize(null);

                var exceptions = new List <Exception>();

                var events = new[]
                {
                    new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                    new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                    new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                };

                // Attempt to write LogEvents that will take forever to retry
                asyncWrapper.WriteAsyncLogEvents(events);
                // Wait a little for the AsyncWrapper to start writing
                System.Threading.Thread.Sleep(50);
                // Close down the AsyncWrapper while busy writing
                asyncWrapper.Close();
                // Close down the RetryingWrapper while busy retrying
                wrapper.Close();
                // Close down the actual target while busy writing
                target.Close();
                // Wait a little for the RetryingWrapper to detect that it has been closed down
                System.Threading.Thread.Sleep(200);
                // The premature abort, causes the exception to be logged
                Assert.NotNull(exceptions[0]);
            });
        }
示例#9
0
        public void AsyncTargetWrapperSyncTest1()
        {
            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper
            {
                WrappedTarget = myTarget,
                Name          = "AsyncTargetWrapperSyncTest1_Wrapper",
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                var               logEvent           = new LogEventInfo();
                Exception         lastException      = null;
                ManualResetEvent  continuationHit    = new ManualResetEvent(false);
                Thread            continuationThread = null;
                AsyncContinuation continuation       =
                    ex =>
                {
                    lastException      = ex;
                    continuationThread = Thread.CurrentThread;
                    continuationHit.Set();
                };

                targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

                // continuation was not hit
                Assert.True(continuationHit.WaitOne(5000));
                Assert.NotSame(continuationThread, Thread.CurrentThread);
                Assert.Null(lastException);
                Assert.Equal(1, myTarget.WriteCount);

                continuationHit.Reset();
                targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
                Assert.True(continuationHit.WaitOne(5000));
                Assert.NotSame(continuationThread, Thread.CurrentThread);
                Assert.Null(lastException);
                Assert.Equal(2, myTarget.WriteCount);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
示例#10
0
        public void FlushOnClosedTargetTest()
        {
            var target = new MyTarget();

            target.Initialize(null);
            target.Close();
            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.CloseCount);

            List <Exception> exceptions = new List <Exception>();

            target.Flush(exceptions.Add);

            Assert.Equal(1, exceptions.Count);
            exceptions.ForEach(Assert.Null);

            // flush was not called
            Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
示例#11
0
        public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero()
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                TimeToSleepBetweenBatches = 0,
                BatchSize      = 4,
                QueueLimit     = 2, // Will make it "sleep" between every second write
                OverflowAction = AsyncTargetWrapperOverflowAction.Block
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                List <KeyValuePair <LogEventInfo, AsyncContinuation> > itemPrepareList = new List <KeyValuePair <LogEventInfo, AsyncContinuation> >(500);
                List <int> itemWrittenList = new List <int>(itemPrepareList.Capacity);
                for (int i = 0; i < itemPrepareList.Capacity; ++i)
                {
                    var logEvent   = new LogEventInfo();
                    int sequenceID = logEvent.SequenceID;
                    itemPrepareList.Add(new KeyValuePair <LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID)));
                }

                long startTicks = Environment.TickCount;
                for (int i = 0; i < itemPrepareList.Count; ++i)
                {
                    var logEvent = itemPrepareList[i].Key;
                    targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value));
                }

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                {
                    System.Threading.Thread.Sleep(1);
                }

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);
                int prevSequenceID = 0;
                for (int i = 0; i < itemWrittenList.Count; ++i)
                {
                    Assert.True(prevSequenceID < itemWrittenList[i]);
                    prevSequenceID = itemWrittenList[i];
                }

                if (!IsAppVeyor())
                {
                    Assert.True(elapsedMilliseconds < 750);    // Skip timing test when running within OpenCover.Console.exe
                }
                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                {
                    System.Threading.Thread.Sleep(1);
                }
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
        public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents()
        {
            var myTarget = new MyTarget { FailCounter = 1 };
            var myTarget2 = new MyTarget();
            var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2);
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = fallbackGroup,
                BufferSize = 10,
            };

            InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup);

            const int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                    };

            // write 9 events - they will all be buffered and no final continuation will be reached
            var eventCounter = 0;
            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.Equal(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.Equal(1, myTarget.WriteCount);
            Assert.Equal(10, myTarget2.WriteCount);

            targetWrapper.Close();
            myTarget.Close();
        }
示例#13
0
        public void BufferingTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
            };

            myTarget.Initialize(null);
            targetWrapper.Initialize(null);

            int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            int hitCount = 0;

            CreateContinuationFunc createAsyncContinuation = 
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                        Interlocked.Increment(ref hitCount);
                    };

            // write 9 events - they will all be buffered and no final continuation will be reached
            int eventCounter = 0;
            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            Assert.AreEqual(10, myTarget.WriteCount);
            for (int i = 0; i < hitCount; ++i)
            {
                Assert.AreSame(Thread.CurrentThread, continuationThread[i]);
                Assert.IsNull(lastException[i]);
            }

            // write 9 more events - they will all be buffered and no final continuation will be reached
            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            // no change
            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            Assert.AreEqual(10, myTarget.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);

            targetWrapper.Flush(
                ex =>
                    {
                        flushException = ex;
                        flushHit.Set();
                    });

            Thread.Sleep(1000);

            flushHit.WaitOne();
            Assert.IsNull(flushException);

            // make sure remaining events were written
            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);
            Assert.AreEqual(1, myTarget.FlushCount);

            // flushes happen on the same thread
            for (int i = 10; i < hitCount; ++i)
            {
                Assert.IsNotNull(continuationThread[i]);
                Assert.AreSame(Thread.CurrentThread, continuationThread[i], "Invalid thread #" + i);
                Assert.IsNull(lastException[i]);
            }

            // flush again - should just invoke Flush() on the wrapped target
            flushHit.Reset();
            targetWrapper.Flush(
                ex =>
                {
                    flushException = ex;
                    flushHit.Set();
                });

            flushHit.WaitOne();
            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);
            Assert.AreEqual(2, myTarget.FlushCount);

            targetWrapper.Close();
            myTarget.Close();
        }
示例#14
0
        public void WriteOnClosedTargetTest()
        {
            var target = new MyTarget();
            target.Initialize(null);
            target.Close();

            var exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            target.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));

            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.CloseCount);

            // write was not called
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);

            // but all callbacks were invoked with null values
            Assert.AreEqual(4, exceptions.Count);
            exceptions.ForEach(Assert.IsNull);
        }
示例#15
0
        public void FlushOnClosedTargetTest()
        {
            var target = new MyTarget();
            target.Initialize(null);
            target.Close();
            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.CloseCount);

            List<Exception> exceptions = new List<Exception>();
            target.Flush(exceptions.Add);

            Assert.AreEqual(1, exceptions.Count);
            exceptions.ForEach(Assert.IsNull);

            // flush was not called
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
示例#16
0
        public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero()
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper() {
                WrappedTarget = myTarget,
                TimeToSleepBetweenBatches = 0,
                BatchSize = 4,
                QueueLimit = 2, // Will make it "sleep" between every second write
                OverflowAction = AsyncTargetWrapperOverflowAction.Block
            };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                List<KeyValuePair<LogEventInfo, AsyncContinuation>> itemPrepareList = new List<KeyValuePair<LogEventInfo, AsyncContinuation>>(2500);
                List<int> itemWrittenList = new List<int>(itemPrepareList.Capacity);
                for (int i = 0; i< itemPrepareList.Capacity; ++i)
                {
                    var logEvent = new LogEventInfo();
                    int sequenceID = logEvent.SequenceID;
                    itemPrepareList.Add(new KeyValuePair<LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID)));
                }

                long startTicks = Environment.TickCount;
                for (int i = 0; i < itemPrepareList.Count; ++i)
                {
                    var logEvent = itemPrepareList[i].Key;
                    targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value));
                }

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                    System.Threading.Thread.Sleep(1);

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);
                int prevSequenceID = 0;
                for (int i = 0; i < itemWrittenList.Count; ++i)
                {
                    Assert.True(prevSequenceID < itemWrittenList[i]);
                    prevSequenceID = itemWrittenList[i];
                }

#if MONO || NET3_5
                Assert.True(elapsedMilliseconds < 2500);    // Skip timing test when running within OpenCover.Console.exe
#endif

                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                    System.Threading.Thread.Sleep(1);
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
示例#17
0
        public void LockingTest()
        {
            var target = new MyTarget();
            target.Initialize(null);

            var mre = new ManualResetEvent(false);

            Exception backgroundThreadException = null;

            Thread t = new Thread(() =>
            {
                try
                {
                    target.BlockingOperation(1000);
                }
                catch (Exception ex)
                {
                    backgroundThreadException = ex;
                }
                finally
                {
                    mre.Set();
                }
            });


            target.Initialize(null);
            t.Start();
            Thread.Sleep(50);
            List<Exception> exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            target.WriteAsyncLogEvents(new[] 
            {
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
            });
            target.Flush(exceptions.Add);
            target.Close();

            exceptions.ForEach(Assert.IsNull);

            mre.WaitOne();
            if (backgroundThreadException != null)
            {
                Assert.Fail(backgroundThreadException.ToString());
            }
        }
示例#18
0
        /// <summary>
        /// Test Fix for https://github.com/NLog/NLog/issues/1069
        /// </summary>
        private void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero(bool forceLockingQueue)
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                TimeToSleepBetweenBatches = 0,
#if NET4_5
                ForceLockingQueue   = forceLockingQueue,
                OptimizeBufferReuse = !forceLockingQueue,
#endif
                BatchSize  = 3,
                QueueLimit = 5, // Will make it "sleep" between every second write
                FullBatchSizeWriteLimit = 1,
                OverflowAction          = AsyncTargetWrapperOverflowAction.Block
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                var itemPrepareList = new List <AsyncLogEventInfo>(500);
                var itemWrittenList = new List <int>(itemPrepareList.Capacity);
                for (int i = 0; i < itemPrepareList.Capacity; ++i)
                {
                    var  logEvent      = new LogEventInfo();
                    int  sequenceID    = logEvent.SequenceID;
                    bool blockConsumer = (itemPrepareList.Capacity / 2) == i;  // Force producers to get into blocking-mode
                    itemPrepareList.Add(logEvent.WithContinuation((ex) => { if (blockConsumer)
                                                                            {
                                                                                Thread.Sleep(125);
                                                                            }
                                                                            itemWrittenList.Add(sequenceID); }));
                }

                var eventProducer0 = new ManualResetEvent(false);
                var eventProducer1 = new ManualResetEvent(false);
                ParameterizedThreadStart producerMethod = (s) =>
                {
                    var eventProducer = (ManualResetEvent)s;
                    if (eventProducer != null)
                    {
                        eventProducer.Set();    // Signal we are ready
                    }
                    int partitionNo = ReferenceEquals(eventProducer, eventProducer1) ? 1 : 0;
                    for (int i = 0; i < itemPrepareList.Count; ++i)
                    {
                        if (i % 2 == partitionNo)
                        {
                            targetWrapper.WriteAsyncLogEvent(itemPrepareList[i]);
                        }
                    }
                };

                Thread producer0 = new Thread(producerMethod);
                producer0.IsBackground = true;
                Thread producer1 = new Thread(producerMethod);
                producer1.IsBackground = true;
                producer1.Start(eventProducer0);
                producer0.Start(eventProducer1);
                Assert.True(eventProducer0.WaitOne(5000), "Producer0 Start Timeout");
                Assert.True(eventProducer1.WaitOne(5000), "Producer1 Start Timeout");

                long startTicks = Environment.TickCount;

                Assert.True(producer0.Join(5000), "Producer0 Complete Timeout");  // Wait for producer0 to complete
                Assert.True(producer1.Join(5000), "Producer1 Complete Timeout");  // Wait for producer1 to complete

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                {
                    Thread.Sleep(1);
                }

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);

                int producer0sequenceID = 0;
                int producer1sequenceID = 0;
                for (int i = 1; i < itemWrittenList.Count; ++i)
                {
                    if (itemWrittenList[i] % 2 == 0)
                    {
                        Assert.True(producer0sequenceID < itemWrittenList[i], "Producer0 invalid sequence");
                        producer0sequenceID = itemWrittenList[i];
                    }
                    else
                    {
                        Assert.True(producer1sequenceID < itemWrittenList[i], "Producer1 invalid sequence");
                        producer1sequenceID = itemWrittenList[i];
                    }
                }

#if NET4_5
                if (!IsAppVeyor())  // Skip timing test when running within OpenCover.Console.exe
#endif
                Assert.InRange(elapsedMilliseconds, 0, 950);

                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                {
                    Thread.Sleep(1);
                }
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
        public void BufferingTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
            };

            InitializeTargets(myTarget, targetWrapper);

            const int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            var hitCount = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                        Interlocked.Increment(ref hitCount);
                    };

            // write 9 events - they will all be buffered and no final continuation will be reached
            var eventCounter = 0;
            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.Equal(0, hitCount);
            Assert.Equal(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.Equal(10, hitCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(10, myTarget.BufferedTotalEvents);
            Assert.Equal(10, myTarget.WriteCount);
            for (var i = 0; i < hitCount; ++i)
            {
                Assert.Same(Thread.CurrentThread, continuationThread[i]);
                Assert.Null(lastException[i]);
            }

            // write 9 more events - they will all be buffered and no final continuation will be reached
            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            // no change
            Assert.Equal(10, hitCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(10, myTarget.BufferedTotalEvents);
            Assert.Equal(10, myTarget.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);

            targetWrapper.Flush(
                ex =>
                {
                    flushException = ex;
                    flushHit.Set();
                });

            flushHit.WaitOne();
            Assert.Null(flushException);

            // make sure remaining events were written
            Assert.Equal(19, hitCount);
            Assert.Equal(2, myTarget.BufferedWriteCount);
            Assert.Equal(19, myTarget.BufferedTotalEvents);
            Assert.Equal(19, myTarget.WriteCount);
            Assert.Equal(1, myTarget.FlushCount);

            // flushes happen on the same thread
            for (var i = 10; i < hitCount; ++i)
            {
                Assert.NotNull(continuationThread[i]);
                Assert.Same(Thread.CurrentThread, continuationThread[i]);
                Assert.Null(lastException[i]);
            }

            // flush again - should just invoke Flush() on the wrapped target
            flushHit.Reset();
            targetWrapper.Flush(
                ex =>
                {
                    flushException = ex;
                    flushHit.Set();
                });

            flushHit.WaitOne();
            Assert.Equal(19, hitCount);
            Assert.Equal(2, myTarget.BufferedWriteCount);
            Assert.Equal(19, myTarget.BufferedTotalEvents);
            Assert.Equal(19, myTarget.WriteCount);
            Assert.Equal(2, myTarget.FlushCount);

            targetWrapper.Close();
            myTarget.Close();
        }
示例#20
0
        public void AsyncTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper
            {
                WrappedTarget = myTarget,
                Name = "AsyncTargetWrapperSyncTest1_Wrapper",
            };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                var logEvent = new LogEventInfo();
                Exception lastException = null;
                ManualResetEvent continuationHit = new ManualResetEvent(false);
                Thread continuationThread = null;
                AsyncContinuation continuation =
                    ex =>
                        {
                            lastException = ex;
                            continuationThread = Thread.CurrentThread;
                            continuationHit.Set();
                        };

                targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

                // continuation was not hit 
                Assert.True(continuationHit.WaitOne(2000));
                Assert.NotSame(continuationThread, Thread.CurrentThread);
                Assert.Null(lastException);
                Assert.Equal(1, myTarget.WriteCount);

                continuationHit.Reset();
                targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
                continuationHit.WaitOne();
                Assert.NotSame(continuationThread, Thread.CurrentThread);
                Assert.Null(lastException);
                Assert.Equal(2, myTarget.WriteCount);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }