private static EndInvokeDelegate <AsyncVoid> MakeVoidDelegate(EndInvokeDelegate endDelegate) { return(ar => { endDelegate(ar); return default(AsyncVoid); }); }
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); } })); }
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)); }
private IAsyncResult BeginInvokeSynchronousActionMethod( ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters, AsyncCallback callback, object state ) { // Frequently called so ensure delegate remains static and arguments do not allocate EndInvokeDelegate <ActionInvocation, ActionResult> endInvokeFunc = ( asyncResult, innerInvokeState ) => { return(innerInvokeState.InvokeSynchronousActionMethod()); }; ActionInvocation endInvokeState = new ActionInvocation( this, controllerContext, actionDescriptor, parameters ); return(AsyncResultWrapper.BeginSynchronous( callback, state, endInvokeFunc, endInvokeState, _invokeActionMethodTag )); }
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)); } }
/// <summary> /// Callback to be used for methods with some return type."/> /// </summary> /// <typeparam name="TR"></typeparam> /// <param name="ar"></param> private static void Callback <TR>(IAsyncResult ar) { object[] stateArr = (object[])ar.AsyncState; Action <TR, object, Exception> callback = (Action <TR, object, Exception>)stateArr[0]; EndInvokeDelegate <TR> action = (EndInvokeDelegate <TR>)stateArr[1]; object state = stateArr[2]; TR returnValue = default(TR); //Call EndInvoke. If there was an exception, it will be caught here. //If there is an exception, it gets tracked inside the EndInvoke. If we do not call EndInvoke, there is a memory leak //and we cannot find whether the method executed without any error. Plus EndInvoke returns the result. //Always call EndInvoke!! try { returnValue = action(ar); } catch (Exception ex) { //pass the exception to the callback callback(returnValue, state, ex); return; } callback(returnValue, state, null); }
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); }
public WrappedAsyncResult(BeginInvokeDelegate beginDelegate, EndInvokeDelegate <TResult> endDelegate, object tag) { _beginDelegateLockObj = new object(); _endExecutedGate = new SingleEntryGate(); _handleCallbackGate = new SingleEntryGate(); _beginDelegate = beginDelegate; _endDelegate = endDelegate; _tag = tag; }
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)); }
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)); }
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)); }
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)); } }
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)); }
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); }
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)); }
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 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; } }
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)); }
// 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); }
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); }
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; } }
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); }
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)); }
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)); }
// 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); }
protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state) { BeginInvokeDelegate delegate4 = null; EndInvokeDelegate delegate5 = null; Action action2 = null; IHttpHandler httpHandler = GetHttpHandler(httpContext); IHttpAsyncHandler httpAsyncHandler = httpHandler as IHttpAsyncHandler; if (httpAsyncHandler != null) { if (delegate4 == null) { delegate4 = (asyncCallback, asyncState) => httpAsyncHandler.BeginProcessRequest(HttpContext.Current, asyncCallback, asyncState); } BeginInvokeDelegate beginDelegate = delegate4; if (delegate5 == null) { delegate5 = delegate(IAsyncResult asyncResult) { httpAsyncHandler.EndProcessRequest(asyncResult); }; } EndInvokeDelegate endDelegate = delegate5; return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _processRequestTag)); } if (action2 == null) { action2 = delegate { httpHandler.ProcessRequest(HttpContext.Current); } } ; Action action = action2; return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag)); }
public virtual IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } if (String.IsNullOrEmpty(actionName)) { throw Error.ParameterCannotBeNullOrEmpty("actionName"); } ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext); ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); if (actionDescriptor != null) { FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor); Action continuation = null; BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) { try { AuthorizationContext authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor); if (authContext.Result != null) { // the auth filter signaled that we should let it short-circuit the request continuation = () => InvokeActionResult(controllerContext, authContext.Result); } else { if (controllerContext.Controller.ValidateRequest) { ValidateRequest(controllerContext); } IDictionary <string, object> parameters = GetParameterValues(controllerContext, actionDescriptor); IAsyncResult asyncResult = BeginInvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters, asyncCallback, asyncState); continuation = () => { ActionExecutedContext postActionContext = EndInvokeActionMethodWithFilters(asyncResult); InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result); }; return(asyncResult); } } catch (ThreadAbortException) { // This type of exception occurs as a result of Response.Redirect(), but we special-case so that // the filters don't see this as an error. throw; } catch (Exception ex) { // something blew up, so execute the exception filters ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex); if (!exceptionContext.ExceptionHandled) { throw; } continuation = () => InvokeActionResult(controllerContext, exceptionContext.Result); } return(BeginInvokeAction_MakeSynchronousAsyncResult(asyncCallback, asyncState)); }; EndInvokeDelegate <bool> endDelegate = delegate(IAsyncResult asyncResult) { try { continuation(); } catch (ThreadAbortException) { // This type of exception occurs as a result of Response.Redirect(), but we special-case so that // the filters don't see this as an error. throw; } catch (Exception ex) { // something blew up, so execute the exception filters ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex); if (!exceptionContext.ExceptionHandled) { throw; } InvokeActionResult(controllerContext, exceptionContext.Result); } return(true); }; return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag)); } else { // Notify the controller that no action was found. return(BeginInvokeAction_ActionNotFound(callback, state)); } }