public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate
            {
                endDelegateWasCalled = true;
                throw new Exception("This is a sample exception.");
            };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
        public void RegisterTask_ResetsOutstandingOperationCountIfBeginMethodThrows()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);

            Func <AsyncCallback, IAsyncResult> beginDelegate = cb =>
            {
                throw new InvalidOperationException("BeginDelegate throws.");
            };
            Action <IAsyncResult> endDelegate = ar =>
            {
                Assert.True(false, "This should never be called.");
            };

            // Act & assert
            Assert.Throws <InvalidOperationException>(
                delegate
            {
                asyncManager.RegisterTask(beginDelegate, endDelegate);
            },
                "BeginDelegate throws."
                );

            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                Assert.Equal(1, asyncManager.OutstandingOperations.Count);
                MockAsyncResult asyncResult = new MockAsyncResult(
                    true /* completedSynchronously */
                    );
                callback(asyncResult);
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate
            {
                endDelegateWasCalled = true;
            };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.False(syncContext.SendWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
Beispiel #4
0
        public void RegisterTask_AsynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ => {
                    Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter shouldn't have been decremented yet.");
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsTrue(syncContext.SendWasCalled, "Asynchronous call to End() should have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
        public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            using (ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */))
            {
                Func <AsyncCallback, IAsyncResult> beginDelegate = callback =>
                {
                    MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        callback(asyncResult);
                        waitHandle.Set();
                    });
                    return(asyncResult);
                };
                Action <IAsyncResult> endDelegate = delegate
                {
                    endDelegateWasCalled = true;
                    throw new Exception("This is a sample exception.");
                };

                // Act
                asyncManager.RegisterTask(beginDelegate, endDelegate);
                waitHandle.WaitOne();

                // Assert
                Assert.True(endDelegateWasCalled);
                Assert.Equal(0, asyncManager.OutstandingOperations.Count);
            }
        }
        public void RegisterTask_AsynchronousCompletion() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ => {
                    Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter shouldn't have been decremented yet.");
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsTrue(syncContext.SendWasCalled, "Asynchronous call to End() should have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
Beispiel #7
0
        public static bool TrySetCanceledAsync <T>(this TaskCompletionSource <T> tcs)
        {
#if NET45
            return(SimpleSynchronizationContext.Enqueue(() => tcs.TrySetCanceled()));
#else
            return(tcs.TrySetCanceled());
#endif
        }
Beispiel #8
0
        public static bool TrySetResultAsync <T>(this TaskCompletionSource <T> tcs, T result)
        {
#if NET45
            return(SimpleSynchronizationContext.Enqueue(() => tcs.TrySetResult(result)));
#else
            return(tcs.TrySetResult(result));
#endif
        }
Beispiel #9
0
        public static bool TrySetExceptionAsync <T>(this TaskCompletionSource <T> tcs, Exception ex)
        {
#if NET45
            return(SimpleSynchronizationContext.Enqueue(() => tcs.TrySetException(ex)));
#else
            return(tcs.TrySetException(ex));
#endif
        }
        public void RegisterTask_ResetsOutstandingOperationCountIfBeginMethodThrows()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);

            Func<AsyncCallback, IAsyncResult> beginDelegate = cb => { throw new InvalidOperationException("BeginDelegate throws."); };
            Action<IAsyncResult> endDelegate = ar => { Assert.True(false, "This should never be called."); };

            // Act & assert
            Assert.Throws<InvalidOperationException>(
                delegate { asyncManager.RegisterTask(beginDelegate, endDelegate); }, "BeginDelegate throws.");

            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
Beispiel #11
0
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsFalse(syncContext.SendWasCalled, "Synchronous call to End() should not have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
Beispiel #12
0
        public static void RunSynchronizationContextTaskSchedulerTests()
        {
            // Remember the current SynchronizationContext, so that we can restore it
            SynchronizationContext previousSC = SynchronizationContext.Current;

            // Now make up a "real" SynchronizationContext and install it
            SimpleSynchronizationContext newSC = new SimpleSynchronizationContext();

            SetSynchronizationContext(newSC);

            // Create a scheduler based on the current SC
            TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext();

            //
            // Launch a Task on scTS, make sure that it is processed in the expected fashion
            //
            bool sideEffect = false;
            Task task       = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS);

            Exception ex = null;

            try
            {
                task.Wait();
            }
            catch (Exception e)
            {
                ex = e;
            }

            Assert.True(task.IsCompleted, "Expected task to have completed");
            Assert.True(ex == null, "Did not expect exception on Wait");
            Assert.True(sideEffect, "Task appears not to have run");
            Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext");

            //
            // Run a Task synchronously on scTS, make sure that it completes
            //
            sideEffect = false;
            Task syncTask = new Task(() => { sideEffect = true; });

            ex = null;
            try
            {
                syncTask.RunSynchronously(scTS);
            }
            catch (Exception e)
            {
                ex = e;
            }

            Assert.True(task.IsCompleted, "Expected task to have completed");
            Assert.True(ex == null, "Did not expect exception on RunSynchronously");
            Assert.True(sideEffect, "Task appears not to have run");
            Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext");

            //
            // Miscellaneous things to test
            //
            Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1");

            // restore original SC
            SetSynchronizationContext(previousSC);
        }
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                Assert.Equal(1, asyncManager.OutstandingOperations.Count);
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.False(syncContext.SendWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
        public void RegisterTask_SynchronousCompletion() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsFalse(syncContext.SendWasCalled, "Synchronous call to End() should not have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
Beispiel #15
0
        public static void RunSynchronizationContextTaskSchedulerTests()
        {
            // Remember the current SynchronizationContext, so that we can restore it
            SynchronizationContext previousSC = SynchronizationContext.Current;

            // Now make up a "real" SynchronizationContext abd install it
            SimpleSynchronizationContext newSC = new SimpleSynchronizationContext();
            SetSynchronizationContext(newSC);

            // Create a scheduler based on the current SC
            TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext();

            //
            // Launch a Task on scTS, make sure that it is processed in the expected fashion
            //
            bool sideEffect = false;
            Task task = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS);

            Exception ex = null;

            try
            {
                task.Wait();
            }
            catch (Exception e)
            {
                ex = e;
            }

            Assert.True(task.IsCompleted, "Expected task to have completed");
            Assert.True(ex == null, "Did not expect exception on Wait");
            Assert.True(sideEffect, "Task appears not to have run");
            Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext");

            // 
            // Run a Task synchronously on scTS, make sure that it completes
            //
            sideEffect = false;
            Task syncTask = new Task(() => { sideEffect = true; });

            ex = null;
            try
            {
                syncTask.RunSynchronously(scTS);
            }
            catch (Exception e)
            {
                ex = e;
            }

            Assert.True(task.IsCompleted, "Expected task to have completed");
            Assert.True(ex == null, "Did not expect exception on RunSynchronously");
            Assert.True(sideEffect, "Task appears not to have run");
            Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext");

            //
            // Miscellaneous things to test
            //
            Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1");

            // restore original SC
            SetSynchronizationContext(previousSC);
        }