public AsyncManager(SynchronizationContext context)
 {
     _context                          = context ?? SynchronizationContextExtensions.GetSynchronizationContext();
     _parameters                       = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
     _outstandingOperations            = new OperationCounter();
     _outstandingOperations.Completed += delegate {
         Finish();
     };
 }
        protected virtual IAsyncResult BeginProcessRequest(
            HttpContextBase context, AsyncCallback callback, object state)
        {
            AppendVersionHeader(context);
            string controllerName = Context.RouteData.GetRequiredValue <string>("controller");

            IControllerFactory factory    = Builder.GetControllerFactory();
            IController        controller = factory.CreateController(Context, controllerName);

            if (controller == null)
            {
                throw Error.CouldNotCreateController(controllerName);
            }

            IAsyncController asyncController = (controller as IAsyncController);

            if (asyncController == null)             // synchronous controller
            {
                Action action = delegate {
                    try
                    {
                        controller.Execute(Context);
                    }
                    finally
                    {
                        factory.ReleaseController(controller);
                    }
                };
                return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _tag));
            }

            // asynchronous controller
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                try
                {
                    return(asyncController.BeginExecute(Context, asyncCallback, asyncState));
                }
                finally
                {
                    factory.ReleaseController(asyncController);
                }
            };
            EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {
                try
                {
                    asyncController.EndExecute(asyncResult);
                }
                finally
                {
                    factory.ReleaseController(asyncController);
                }
            };

            return(AsyncResultWrapper.Begin(AsyncTask.WrapCallbackForSynchronizedExecution(callback,
                                                                                           SynchronizationContextExtensions.GetSynchronizationContext()),
                                            state, beginDelegate, endDelegate, _tag));
        }