Example #1
0
        public async Task AsyncMethodReturnsTaskOfT()
        {
            const string expected = "foo";

            var actual = await AsyncMethods
                         .WaitASecondAndReturnAValueAsync(expected);

            Assert.AreEqual(expected, actual);
        }
Example #2
0
        public void SomeProblemWithGetAwaiterGetResult()
        {
            var blockingSyncContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(blockingSyncContext);
            var theValue = AsyncMethods
                           .WaitASecondAndReturnAValueAsync("this too is doomed")
                           .GetAwaiter()
                           .GetResult();
        }
Example #3
0
        public void ItCreatesADeadLockWhenCertainSyncContextsGetInvolved()
        {
            var blockingSyncContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(blockingSyncContext);

            // Result is invoked on the same thread as the blocking sync context
            // Because the sync context blocked when calling the async method,
            // The call to result is deadlocked as it's waiting for the original call
            // to release the thread.
            // A way to see this visually is to execute this from a GUI, it would become non responsive.
            var theValue = AsyncMethods
                           .WaitASecondAndReturnAValueAsync("this is doomed to deadlock")
                           .Result;
        }
Example #4
0
        public void HowDoIFixThisDeadLockByAllowingCompletionOnADifferentThread()
        {
            var blockingSyncContext = new WindowsFormsSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(blockingSyncContext);
            Func <Task <string> > returnValueFunc = () => AsyncMethods
                                                    .WaitASecondAndReturnAValueAsync("this works around it");

            //this now executes on a different thread
            //and wont deadlock when calling result
            var theValue = Task
                           .Run(returnValueFunc)
                           .Result;

            Assert.AreEqual("this works around it", theValue);
        }