Beispiel #1
0
        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            IHttpHandler      httpHandler      = GetHttpHandler(httpContext);
            IHttpAsyncHandler httpAsyncHandler = httpHandler as IHttpAsyncHandler;

            if (httpAsyncHandler != null)
            {
                // asynchronous handler

                // Ensure delegates continue to use the C# Compiler static delegate caching optimization.
                BeginInvokeDelegate <IHttpAsyncHandler> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, IHttpAsyncHandler innerHandler)
                {
                    return(innerHandler.BeginProcessRequest(HttpContext.Current, asyncCallback, asyncState));
                };
                EndInvokeVoidDelegate <IHttpAsyncHandler> endDelegate = delegate(IAsyncResult asyncResult, IHttpAsyncHandler innerHandler)
                {
                    innerHandler.EndProcessRequest(asyncResult);
                };
                return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, httpAsyncHandler, _processRequestTag));
            }
            else
            {
                // synchronous handler
                Action action = delegate
                {
                    httpHandler.ProcessRequest(HttpContext.Current);
                };
                return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag));
            }
        }
Beispiel #2
0
        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            IHttpHandler      httpHandler      = GetHttpHandler(httpContext);
            IHttpAsyncHandler httpAsyncHandler = httpHandler as IHttpAsyncHandler;

            if (httpAsyncHandler != null)
            {
                // asynchronous handler
                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
                {
                    return(httpAsyncHandler.BeginProcessRequest(HttpContext.Current, asyncCallback, asyncState));
                };
                EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult)
                {
                    httpAsyncHandler.EndProcessRequest(asyncResult);
                };
                return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _processRequestTag));
            }
            else
            {
                // synchronous handler
                Action action = delegate
                {
                    httpHandler.ProcessRequest(HttpContext.Current);
                };
                return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag));
            }
        }
        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            return(SecurityUtil.ProcessInApplicationTrust(() =>
            {
                IController controller;
                IControllerFactory factory;
                ProcessRequestInit(httpContext, out controller, out factory);

                IAsyncController asyncController = controller as IAsyncController;
                if (asyncController != null)
                {
                    // asynchronous controller
                    BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
                    {
                        try
                        {
                            return asyncController.BeginExecute(RequestContext, asyncCallback, asyncState);
                        }
                        catch
                        {
                            factory.ReleaseController(asyncController);
                            throw;
                        }
                    };

                    EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult)
                    {
                        try
                        {
                            asyncController.EndExecute(asyncResult);
                        }
                        finally
                        {
                            factory.ReleaseController(asyncController);
                        }
                    };

                    SynchronizationContext syncContext = SynchronizationContextUtil.GetSynchronizationContext();
                    AsyncCallback newCallback = AsyncUtil.WrapCallbackForSynchronizedExecution(callback, syncContext);
                    return AsyncResultWrapper.Begin(newCallback, state, beginDelegate, endDelegate, _processRequestTag);
                }
                else
                {
                    // synchronous controller
                    Action action = delegate
                    {
                        try
                        {
                            controller.Execute(RequestContext);
                        }
                        finally
                        {
                            factory.ReleaseController(controller);
                        }
                    };

                    return AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag);
                }
            }));
        }
Beispiel #4
0
        protected internal virtual IAsyncResult BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList <IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            Func <ActionExecutedContext> endContinuation = null;

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                AsyncInvocationWithFilters invocation = new AsyncInvocationWithFilters(this, controllerContext, actionDescriptor, filters, parameters, asyncCallback, asyncState);

                const int StartingFilterIndex = 0;
                endContinuation = invocation.InvokeActionMethodFilterAsynchronouslyRecursive(StartingFilterIndex);

                if (invocation.InnerAsyncResult != null)
                {
                    // we're just waiting for the inner result to complete
                    return(invocation.InnerAsyncResult);
                }
                else
                {
                    // something was short-circuited and the action was not called, so this was a synchronous operation
                    SimpleAsyncResult newAsyncResult = new SimpleAsyncResult(asyncState);
                    newAsyncResult.MarkCompleted(completedSynchronously: true, callback: asyncCallback);
                    return(newAsyncResult);
                }
            };

            EndInvokeDelegate <ActionExecutedContext> endDelegate = delegate(IAsyncResult asyncResult)
            {
                return(endContinuation());
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodWithFiltersTag));
        }
 public WrappedAsyncVoid(BeginInvokeDelegate<TState> beginDelegate, EndInvokeVoidDelegate<TState> endDelegate, TState state, object tag, SynchronizationContext callbackSyncContext)
     : base(tag, callbackSyncContext)
 {
     _beginDelegate = beginDelegate;
     _endDelegate = endDelegate;
     _state = state;
 }
        public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate,
                                         EndInvokeDelegate <TResult> endDelegate, object tag, int timeout)
        {
            WrappedAsyncResult <TResult> asyncResult = new WrappedAsyncResult <TResult>(beginDelegate, endDelegate, tag);

            asyncResult.Begin(callback, state, timeout);
            return(asyncResult);
        }
Beispiel #7
0
        private static IAsyncResult ActionNotFound(AsyncCallback callback, object state)
        {
            BeginInvokeDelegate      beginDelegate = MakeSynchronousAsyncResult;
            EndInvokeDelegate <bool> endDelegate   = delegate(IAsyncResult asyncResult) {
                return(false);
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeTag));
        }
Beispiel #8
0
        private void button4_Click(object sender, EventArgs e)
        {
            var          caller = new BeginInvokeDelegate(LoadJokeData);
            IAsyncResult result = caller.BeginInvoke(null, null);

            result.AsyncWaitHandle.WaitOne();
            caller.EndInvoke(result);
            result.AsyncWaitHandle.Close();
        }
        public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            AsyncManager asyncManager = GetAsyncManager(controllerContext.Controller);

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                // call the XxxAsync() method
                ParameterInfo[] parameterInfos     = AsyncMethodInfo.GetParameters();
                var             rawParameterValues = from parameterInfo in parameterInfos
                                                     select ExtractParameterFromDictionary(parameterInfo, parameters, AsyncMethodInfo);

                object[] parametersArray = rawParameterValues.ToArray();

                TriggerListener   listener    = new TriggerListener();
                SimpleAsyncResult asyncResult = new SimpleAsyncResult(asyncState);

                // hook the Finished event to notify us upon completion
                Trigger finishTrigger = listener.CreateTrigger();
                asyncManager.Finished += delegate { finishTrigger.Fire(); };
                asyncManager.OutstandingOperations.Increment();

                // to simplify the logic, force the rest of the pipeline to execute in an asynchronous callback
                listener.SetContinuation(() => ThreadPool.QueueUserWorkItem(_ => asyncResult.MarkCompleted(false /* completedSynchronously */, asyncCallback)));

                // the inner operation might complete synchronously, so all setup work has to be done before this point
                ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(AsyncMethodInfo);
                dispatcher.Execute(controllerContext.Controller, parametersArray); // ignore return value from this method

                // now that the XxxAsync() method has completed, kick off any pending operations
                asyncManager.OutstandingOperations.Decrement();
                listener.Activate();
                return(asyncResult);
            };

            EndInvokeDelegate <object> endDelegate = delegate(IAsyncResult asyncResult) {
                // call the XxxCompleted() method
                ParameterInfo[] completionParametersInfos    = CompletedMethodInfo.GetParameters();
                var             rawCompletionParameterValues = from parameterInfo in completionParametersInfos
                                                               select ExtractParameterOrDefaultFromDictionary(parameterInfo, asyncManager.Parameters);

                object[] completionParametersArray = rawCompletionParameterValues.ToArray();

                ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(CompletedMethodInfo);
                object actionReturnValue          = dispatcher.Execute(controllerContext.Controller, completionParametersArray);
                return(actionReturnValue);
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _executeTag, asyncManager.Timeout));
        }
 public WrappedAsyncResult(BeginInvokeDelegate beginDelegate, EndInvokeDelegate <TResult> endDelegate, object tag)
 {
     _beginDelegateLockObj = new object();
     _endExecutedGate      = new SingleEntryGate();
     _handleCallbackGate   = new SingleEntryGate();
     _beginDelegate        = beginDelegate;
     _endDelegate          = endDelegate;
     _tag = tag;
 }
        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));
        }
Beispiel #12
0
 public WrappedAsyncResult(
     BeginInvokeDelegate beginDelegate,
     EndInvokeDelegate <TResult> endDelegate,
     object tag,
     SynchronizationContext callbackSyncContext
     ) : base(tag, callbackSyncContext)
 {
     _beginDelegate = beginDelegate;
     _endDelegate   = endDelegate;
 }
        public virtual IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            Contract.Assert(controllerContext.RouteData != null);
            if (String.IsNullOrEmpty(actionName) && !controllerContext.RouteData.HasDirectRouteMatch())
            {
                throw Error.ParameterCannotBeNullOrEmpty("actionName");
            }

            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);
            ActionDescriptor     actionDescriptor     = FindAction(controllerContext, controllerDescriptor, actionName);

            if (actionDescriptor != null)
            {
                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
                {
                    var task = InvokeActionAsync(controllerContext, actionDescriptor);
                    var tcs  = new TaskCompletionSource <bool>(asyncState);
                    task.ContinueWith(t =>
                    {
                        if (t.IsFaulted)
                        {
                            tcs.TrySetException(t.Exception.InnerExceptions);
                        }
                        else if (t.IsCanceled)
                        {
                            tcs.TrySetCanceled();
                        }
                        else
                        {
                            tcs.TrySetResult(t.Result);
                        }
                        if (asyncCallback != null)
                        {
                            asyncCallback(tcs.Task);
                        }
                    }, TaskContinuationOptions.ExecuteSynchronously);
                    return(tcs.Task);
                };
                EndInvokeDelegate <bool> endDelegate = delegate(IAsyncResult asyncResult)
                {
                    return(((Task <bool>)asyncResult).GetAwaiter().GetResult());
                };
                return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag));
            }
            else
            {
                // Notify the controller that no action was found.
                return(BeginInvokeAction_ActionNotFound(callback, state));
            }
        }
Beispiel #14
0
        protected virtual IAsyncResult BeginExecute(
            RequestContext requestContext,
            AsyncCallback callback,
            object state
            )
        {
            if (DisableAsyncSupport)
            {
                // For backwards compat, we can disallow async support and just chain to the sync Execute() function.
                Action action = () =>
                {
                    Execute(requestContext);
                };

                return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _executeTag));
            }
            else
            {
                if (requestContext == null)
                {
                    throw new ArgumentNullException("requestContext");
                }

                // Support Asynchronous behavior.
                // Execute/ExecuteCore are no longer called.

                VerifyExecuteCalledOnce();
                Initialize(requestContext);

                // Ensure delegates continue to use the C# Compiler static delegate caching optimization.
                BeginInvokeDelegate <Controller> beginDelegate = (
                    AsyncCallback asyncCallback,
                    object callbackState,
                    Controller controller
                    ) =>
                {
                    return(controller.BeginExecuteCore(asyncCallback, callbackState));
                };
                EndInvokeVoidDelegate <Controller> endDelegate = (
                    IAsyncResult asyncResult,
                    Controller controller
                    ) =>
                {
                    controller.EndExecuteCore(asyncResult);
                };
                return(AsyncResultWrapper.Begin(
                           callback,
                           state,
                           beginDelegate,
                           endDelegate,
                           this,
                           _executeTag
                           ));
            }
        }
        // wraps a synchronous operation in an asynchronous wrapper, but still completes synchronously

        public static IAsyncResult BeginSynchronous<TResult, TState>(AsyncCallback callback, object callbackState, EndInvokeDelegate<TState, TResult> func, TState funcState, object tag)
        {
            // Frequently called, so use static delegates

            // Inline delegates that take a generic argument from a generic method don't get cached by the compiler so use a field from a static generic class
            BeginInvokeDelegate<TState> beginDelegate = CachedDelegates<TState>.CompletedBeginInvoke;

            // Pass in the blocking function as the End() method
            WrappedAsyncResult<TResult, TState> asyncResult = new WrappedAsyncResult<TResult, TState>(beginDelegate, func, funcState, tag, callbackSyncContext: null);
            asyncResult.Begin(callback, callbackState, Timeout.Infinite);
            return asyncResult;
        }
Beispiel #16
0
        public override IAsyncResult BeginExecute(Request request, AsyncCallback callback, object state)
        {
            var responseTask = new TaskCompletionSource <Response>();

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                if (_commandService.WaitingRequests > ConfigurationSettings.MaxRequests)
                {
                    responseTask.SetResult(Response.ServerTooBusy);
                    return(CreateInnerAsyncResult(asyncCallback, asyncState));
                }

                Type type;

                if (!BasicTypes.CommandTypes.TryGetValue(request.Header.GetIfKeyNotFound("Type"), out type))
                {
                    responseTask.SetResult(Response.UnknownType);
                    return(CreateInnerAsyncResult(asyncCallback, asyncState));
                }

                ICommand command;
                try
                {
                    command = (ICommand)_serializer.Deserialize(request.Body, type);
                }
                catch (Exception)
                {
                    responseTask.TrySetResult(Response.ParsingFailure);
                    return(CreateInnerAsyncResult(asyncCallback, asyncState));
                }

                var timeout    = request.Header.GetIfKeyNotFound("Timeout", "0").ChangeIfError(0);
                var returnMode = (CommandReturnMode)request.Header.GetIfKeyNotFound("Mode", "1").ChangeIfError(1);
                var result     = _commandService.Execute(command, returnMode, timeout);
                var message    = _serializer.Serialize(result);
                responseTask.TrySetResult(new Response(200, message));


                return(CreateInnerAsyncResult(asyncCallback, asyncState));
            };

            EndInvokeDelegate <Response> endDelegate =
                delegate { return(responseTask.Task.Result); };

            return(WrappedAsyncResult <Response> .Begin(
                       callback,
                       state,
                       beginDelegate,
                       endDelegate,
                       null,
                       Timeout.Infinite));
        }
Beispiel #17
0
        protected virtual IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
        {
            // If code in this method needs to be updated, please also check the ExecuteCore() method
            // of Controller to see if that code also must be updated.
            PossiblyLoadTempData();
            try
            {
                string              actionName   = RouteData.GetRequiredString("action");
                IActionInvoker      invoker      = ActionInvoker;
                IAsyncActionInvoker asyncInvoker = invoker as IAsyncActionInvoker;
                if (asyncInvoker != null)
                {
                    // asynchronous invocation
                    // Ensure delegates continue to use the C# Compiler static delegate caching optimization.
                    BeginInvokeDelegate <ExecuteCoreState> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, ExecuteCoreState innerState)
                    {
                        return(innerState.AsyncInvoker.BeginInvokeAction(innerState.Controller.ControllerContext, innerState.ActionName, asyncCallback, asyncState));
                    };

                    EndInvokeVoidDelegate <ExecuteCoreState> endDelegate = delegate(IAsyncResult asyncResult, ExecuteCoreState innerState)
                    {
                        if (!innerState.AsyncInvoker.EndInvokeAction(asyncResult))
                        {
                            innerState.Controller.HandleUnknownAction(innerState.ActionName);
                        }
                    };
                    ExecuteCoreState executeState = new ExecuteCoreState()
                    {
                        Controller = this, AsyncInvoker = asyncInvoker, ActionName = actionName
                    };

                    return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, executeState, _executeCoreTag));
                }
                else
                {
                    // synchronous invocation
                    Action action = () =>
                    {
                        if (!invoker.InvokeAction(ControllerContext, actionName))
                        {
                            HandleUnknownAction(actionName);
                        }
                    };
                    return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _executeCoreTag));
                }
            }
            catch
            {
                PossiblySaveTempData();
                throw;
            }
        }
        public static IAsyncResult BeginSynchronous <TResult>(AsyncCallback callback, object state, Func <TResult> func, object tag)
        {
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                var result2 = new SimpleAsyncResult(asyncState);
                result2.MarkCompleted(true, asyncCallback);
                return(result2);
            };
            EndInvokeDelegate <TResult> endDelegate = (_ => func());
            var result = new WrappedAsyncResult <TResult>(beginDelegate, endDelegate, tag);

            result.Begin(callback, state, -1);
            return(result);
        }
Beispiel #19
0
        private IAsyncResult BeginInvokeAsynchronousActionMethod(ControllerContext controllerContext, AsyncActionDescriptor actionDescriptor, IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                return(actionDescriptor.BeginExecute(controllerContext, parameters, asyncCallback, asyncState));
            };

            EndInvokeDelegate <ActionResult> endDelegate = delegate(IAsyncResult asyncResult) {
                object       returnValue = actionDescriptor.EndExecute(asyncResult);
                ActionResult result      = CreateActionResult(controllerContext, actionDescriptor, returnValue);
                return(result);
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodTag));
        }
        protected virtual IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
        {
            // If code in this method needs to be updated, please also check the ExecuteCore() method
            // of Controller to see if that code also must be updated.

            PossiblyLoadTempData();
            try
            {
                string              actionName   = RouteData.GetRequiredString("action");
                IActionInvoker      invoker      = ActionInvoker;
                IAsyncActionInvoker asyncInvoker = invoker as IAsyncActionInvoker;
                if (asyncInvoker != null)
                {
                    // asynchronous invocation
                    BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
                    {
                        return(asyncInvoker.BeginInvokeAction(ControllerContext, actionName, asyncCallback, asyncState));
                    };

                    EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult)
                    {
                        if (!asyncInvoker.EndInvokeAction(asyncResult))
                        {
                            HandleUnknownAction(actionName);
                        }
                    };

                    return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _executeCoreTag));
                }
                else
                {
                    // synchronous invocation
                    Action action = () =>
                    {
                        if (!invoker.InvokeAction(ControllerContext, actionName))
                        {
                            HandleUnknownAction(actionName);
                        }
                    };
                    return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _executeCoreTag));
                }
            }
            catch
            {
                PossiblySaveTempData();
                throw;
            }
        }
Beispiel #21
0
        public override IAsyncResult BeginExecute(Request request, AsyncCallback callback, object state)
        {
            var responseTask = new TaskCompletionSource <Response>();

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                var  typeName = request.Header.GetIfKeyNotFound("Type");
                Type type;
                if (!_resultTypeMap.TryGetValue(typeName, out type))
                {
                    responseTask.SetResult(Response.UnknownType);
                    return(CreateInnerAsyncResult(asyncCallback, asyncState));
                }

                var traceId = request.Header.GetIfKeyNotFound("TraceId");
                if (string.IsNullOrEmpty(traceId))
                {
                    var errorMessage = string.Format("Receive a empty traceId Reply Type({0}).", typeName);
                    responseTask.SetResult(new Response(500, errorMessage));
                    return(CreateInnerAsyncResult(asyncCallback, asyncState));
                }

                IResult result;
                try
                {
                    result = (IResult)_serializer.Deserialize(request.Body, type);
                }
                catch (Exception)
                {
                    responseTask.TrySetResult(Response.ParsingFailure);
                    return(CreateInnerAsyncResult(asyncCallback, asyncState));
                }

                _resultBus.Send(result, traceId);
                return(CreateInnerAsyncResult(asyncCallback, asyncState));
            };

            EndInvokeDelegate <Response> endDelegate =
                delegate { return(responseTask.Task.Result); };

            return(WrappedAsyncResult <Response> .Begin(
                       callback,
                       state,
                       beginDelegate,
                       endDelegate,
                       null,
                       Timeout.Infinite));
        }
        protected internal virtual IAsyncResult BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList <IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            Func <ActionExecutedContext> endContinuation = null;

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                ActionExecutingContext preContext       = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);
                IAsyncResult           innerAsyncResult = null;

                Func <Func <ActionExecutedContext> > beginContinuation = () =>
                {
                    innerAsyncResult = BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters, asyncCallback, asyncState);
                    return(() =>
                           new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */)
                    {
                        Result = EndInvokeActionMethod(innerAsyncResult)
                    });
                };

                // need to reverse the filter list because the continuations are built up backward
                Func <Func <ActionExecutedContext> > thunk = filters.Reverse().Aggregate(beginContinuation,
                                                                                         (next, filter) => () => InvokeActionMethodFilterAsynchronously(filter, preContext, next));
                endContinuation = thunk();

                if (innerAsyncResult != null)
                {
                    // we're just waiting for the inner result to complete
                    return(innerAsyncResult);
                }
                else
                {
                    // something was short-circuited and the action was not called, so this was a synchronous operation
                    SimpleAsyncResult newAsyncResult = new SimpleAsyncResult(asyncState);
                    newAsyncResult.MarkCompleted(true /* completedSynchronously */, asyncCallback);
                    return(newAsyncResult);
                }
            };

            EndInvokeDelegate <ActionExecutedContext> endDelegate = delegate(IAsyncResult asyncResult)
            {
                return(endContinuation());
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodWithFiltersTag));
        }
        public override IAsyncResult BeginExecute(ControllerContext context,
                                                  IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            Precondition.Require(context, () => Error.ArgumentNull("context"));
            Precondition.Require(parameters, () => Error.ArgumentNull("parameters"));

            AsyncManager asyncManager = GetAsyncManager(context.Controller);

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                object[] parameterValues = _entryMethod.GetParameters()
                                           .Select(p => ExtractParameter(p, parameters, _entryMethod))
                                           .ToArray();

                TriggerListener listener    = new TriggerListener();
                MvcAsyncResult  asyncResult = new MvcAsyncResult(asyncState);

                Trigger finishTrigger = listener.CreateTrigger();
                asyncManager.Finished += delegate {
                    finishTrigger.Fire();
                };
                asyncManager.OutstandingOperations.Increment();
                listener.SetContinuation(() => ThreadPool.QueueUserWorkItem(_ =>
                                                                            asyncResult.MarkCompleted(false, asyncCallback)));

                DispatcherCache.GetDispatcher(_entryMethod)
                .Execute(context.Controller, parameterValues);

                asyncManager.OutstandingOperations.Decrement();
                listener.Activate();

                return(asyncResult);
            };

            EndInvokeDelegate <object> endDelegate = delegate(IAsyncResult asyncResult) {
                object[] parameterValues = _completedMethod.GetParameters()
                                           .Select(p => ExtractParameter(p, parameters, _completedMethod))
                                           .ToArray();

                return(DispatcherCache.GetDispatcher(_completedMethod)
                       .Execute(context.Controller, parameterValues));
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate,
                                            endDelegate, _executeTag, asyncManager.Timeout));
        }
Beispiel #24
0
        // kicks off an asynchronous operation

        public static IAsyncResult Begin <TResult>(
            AsyncCallback callback,
            object state,
            BeginInvokeDelegate beginDelegate,
            EndInvokeDelegate <TResult> endDelegate,
            object tag  = null,
            int timeout = Timeout.Infinite
            )
        {
            WrappedAsyncResult <TResult> asyncResult = new WrappedAsyncResult <TResult>(
                beginDelegate,
                endDelegate,
                tag,
                callbackSyncContext: null
                );

            asyncResult.Begin(callback, state, timeout);
            return(asyncResult);
        }
Beispiel #25
0
        public static IAsyncResult Begin <TResult, TState>(
            AsyncCallback callback,
            object callbackState,
            BeginInvokeDelegate <TState> beginDelegate,
            EndInvokeDelegate <TState, TResult> endDelegate,
            TState invokeState,
            object tag  = null,
            int timeout = Timeout.Infinite,
            SynchronizationContext callbackSyncContext = null
            )
        {
            WrappedAsyncResult <TResult, TState> asyncResult = new WrappedAsyncResult <
                TResult,
                TState
                >(beginDelegate, endDelegate, invokeState, tag, callbackSyncContext);

            asyncResult.Begin(callback, callbackState, timeout);
            return(asyncResult);
        }
Beispiel #26
0
        public static IAsyncResult BeginSynchronous <TResult>(AsyncCallback callback, object state, Func <TResult> func, object tag)
        {
            // Begin() doesn't perform any work on its own and returns immediately.
            BeginInvokeDelegate beginDelegate = (asyncCallback, asyncState) => {
                SimpleAsyncResult innerAsyncResult = new SimpleAsyncResult(asyncState);
                innerAsyncResult.MarkCompleted(true /* completedSynchronously */, asyncCallback);
                return(innerAsyncResult);
            };

            // The End() method blocks.
            EndInvokeDelegate <TResult> endDelegate = _ => {
                return(func());
            };

            WrappedAsyncResult <TResult> asyncResult = new WrappedAsyncResult <TResult>(beginDelegate, endDelegate, tag);

            asyncResult.Begin(callback, state, Timeout.Infinite);
            return(asyncResult);
        }
        protected virtual IAsyncResult OnBeginExecute(AsyncCallback callback, object state)
        {
            LoadTempData();

            try
            {
                string actionName = RouteData.GetRequiredValue <string>("action");

                IActionExecutor      executor      = ActionExecutor;
                IAsyncActionExecutor asyncExecutor = (executor as IAsyncActionExecutor);

                if (asyncExecutor != null)
                {
                    BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                        return(asyncExecutor.BeginInvokeAction(Context, actionName, asyncCallback, asyncState, new ValueDictionary()));
                    };
                    EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {
                        if (!asyncExecutor.EndInvokeAction(asyncResult))
                        {
                            HandleUnknownAction(actionName);
                        }
                    };
                    return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _tag));
                }
                else
                {
                    Action action = () => {
                        if (!executor.InvokeAction(Context, actionName, null))
                        {
                            HandleUnknownAction(actionName);
                        }
                    };
                    return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _tag));
                }
            }
            catch
            {
                SaveTempData();
                throw;
            }
        }
Beispiel #28
0
        public static IAsyncResult BeginSynchronous <TResult>(AsyncCallback callback,
                                                              object state, Func <TResult> func, object tag)
        {
            BeginInvokeDelegate beginDelegate = (asyncCallback, asyncState) => {
                MvcAsyncResult inner = new MvcAsyncResult(asyncState);
                inner.MarkCompleted(true, asyncCallback);

                return(inner);
            };

            EndInvokeDelegate <TResult> endDelegate = _ => {
                return(func());
            };

            WrappedAsyncResult <TResult> result =
                new WrappedAsyncResult <TResult>(beginDelegate, endDelegate, tag);

            result.Begin(callback, state, Timeout.Infinite);

            return(result);
        }
Beispiel #29
0
        protected virtual IAsyncResult BeginProcessRequest(
            HttpContextBase context, AsyncCallback callback, object state)
        {
            IHttpHandler      handler      = GetHttpHandler(context);
            IHttpAsyncHandler asyncHandler = (handler as IHttpAsyncHandler);

            if (asyncHandler == null)
            {
                Action action = delegate {
                    handler.ProcessRequest(context.Unwrap());
                };
                return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _tag));
            }
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                return(asyncHandler.BeginProcessRequest(context.Unwrap(), asyncCallback, asyncState));
            };
            EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {
                asyncHandler.EndProcessRequest(asyncResult);
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _tag));
        }
Beispiel #30
0
        protected virtual IAsyncResult BeginInvokeActionFilters(ControllerContext context,
                                                                ActionDescriptor action, ICollection <IActionFilter> filters, IDictionary <string, object> parameters,
                                                                AsyncCallback callback, object state)
        {
            Func <ActionExecutedContext> endContinuation = null;

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                ActionExecutionContext preContext       = new ActionExecutionContext(context, action);
                IAsyncResult           innerAsyncResult = null;

                Func <Func <ActionExecutedContext> > beginContinuation = () => {
                    innerAsyncResult = BeginInvokeActionMethod(context, action, parameters, asyncCallback, asyncState);
                    return(() => new ActionExecutedContext(preContext, null)
                    {
                        Result = EndInvokeActionMethod(innerAsyncResult)
                    });
                };
                Func <Func <ActionExecutedContext> > thunk = filters.Reverse().Aggregate(beginContinuation,
                                                                                         (next, filter) => () => InvokeActionFilterAsynchronously(filter, preContext, next));
                endContinuation = thunk();

                if (innerAsyncResult != null)
                {
                    return(innerAsyncResult);
                }
                else
                {
                    MvcAsyncResult newAsyncResult = new MvcAsyncResult(asyncState);
                    newAsyncResult.MarkCompleted(true, asyncCallback);

                    return(newAsyncResult);
                }
            };
            EndInvokeDelegate <ActionExecutedContext> endDelegate = delegate(IAsyncResult asyncResult) {
                return(endContinuation());
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeMethodFiltersTag));
        }
 private static IAsyncResult BeginInvokeAction_ActionNotFound(AsyncCallback callback, object state)
 {
     BeginInvokeDelegate beginDelegate = new BeginInvokeDelegate(BeginInvokeAction_MakeSynchronousAsyncResult);
     EndInvokeDelegate<bool> endDelegate = (IAsyncResult asyncResult) => false;
     return AsyncResultWrapper.Begin<bool>(callback, state, beginDelegate, endDelegate, _invokeActionTag);
 }