C# (CSharp) AsyncCallback Code Examples

C# (CSharp) AsyncCallback - 30 examples found. These are the top rated real world C# (CSharp) examples of AsyncCallback extracted from open source projects. You can rate examples to help us improve the quality of examples
Frequently Used Methods
Example #1
0
        protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state)
        {
            StructuredTracer.Correlate();

            try
            {
                if (command is SaveWorkflowCommand)
                {
                    return new TypedCompletedAsyncResult<bool>(SaveWorkflow(context, (SaveWorkflowCommand)command), callback, state);
                }
                else if (command is LoadWorkflowCommand)
                {
                    return new TypedCompletedAsyncResult<bool>(LoadWorkflow(context, (LoadWorkflowCommand)command), callback, state);
                }
                else if (command is CreateWorkflowOwnerCommand)
                {
                    return new TypedCompletedAsyncResult<bool>(CreateWorkflowOwner(context, (CreateWorkflowOwnerCommand)command), callback, state);
                }
                else if (command is DeleteWorkflowOwnerCommand)
                {
                    return new TypedCompletedAsyncResult<bool>(DeleteWorkflowOwner(context, (DeleteWorkflowOwnerCommand)command), callback, state);
                }
                return new TypedCompletedAsyncResult<bool>(false, callback, state);
            }
            catch (Exception e)
            {
                return new TypedCompletedAsyncResult<Exception>(e, callback, state);
            }
        }
 internal NonEntityOperationResult(object source, HttpWebRequest request, AsyncCallback callback, object state)
 {
   this.source = source;
   this.request = request;
   this.userCallback = callback;
   this.userState = state;
 }
        public ICancellableAsyncResult BeginOpenRead(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state)
        {
            StorageAsyncResult<Stream> storageAsyncResult = new StorageAsyncResult<Stream>(callback, state);

            ICancellableAsyncResult result = this.BeginFetchAttributes(
                accessCondition,
                options,
                operationContext,
                ar =>
                {
                    try
                    {
                        this.EndFetchAttributes(ar);
                        storageAsyncResult.UpdateCompletedSynchronously(ar.CompletedSynchronously);
                        AccessCondition streamAccessCondition = AccessCondition.CloneConditionWithETag(accessCondition, this.Properties.ETag);
                        BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, this.BlobType, this.ServiceClient, false);
                        storageAsyncResult.Result = new BlobReadStream(this, streamAccessCondition, modifiedOptions, operationContext);
                        storageAsyncResult.OnComplete();
                    }
                    catch (Exception e)
                    {
                        storageAsyncResult.OnComplete(e);
                    }
                },
                null /* state */);

            storageAsyncResult.CancelDelegate = result.Cancel;
            return storageAsyncResult;
        }
 public IAsyncResult BeginTryReceiveRequest(
     TimeSpan timeout, AsyncCallback callback, 
     object state)
 {
     ValidateTimeSpan(timeout);
     return this.requestQueue.BeginDequeue(timeout, callback, state);
 }
    static int Main()
    {
        byte [] buf = new byte [1];
        AsyncCallback ac = new AsyncCallback (async_callback);
        IAsyncResult ar;
        int sum0 = 0;

        FileStream s = new FileStream ("async_read.cs",  FileMode.Open);

        s.Position = 0;
        sum0 = 0;
        while (s.Read (buf, 0, 1) == 1)
            sum0 += buf [0];

        s.Position = 0;

        do {
            ar = s.BeginRead (buf, 0, 1, ac, buf);
        } while (s.EndRead (ar) == 1);
        sum -= buf [0];

        Thread.Sleep (100);

        s.Close ();

        Console.WriteLine ("CSUM: " + sum + " " + sum0);
        if (sum != sum0)
            return 1;

        return 0;
    }
Example #6
0
        //Hacking asynchronous file IO just to make the interface consistent - there's not much performance benefit otheriwse
        public override IAsyncResult BeginDownloadXml(Uri feeduri, AsyncCallback callback)
        {
            if (!this.PingFeed(feeduri)) throw new MissingFeedException(string.Format("Was unable to open local XML file {0}", feeduri.LocalPath));

            return FeedWorkerDelegate.BeginInvoke(feeduri, callback, new FeedTuple());

        }
 public static void Main()
 {
     foo_delegate
     d
     =
     new
     foo_delegate
     (function);
     AsyncCallback
     ac
     =
     new
     AsyncCallback
     (async_callback);
     IAsyncResult
     ar1
     =
     d.BeginInvoke
     (ac,
     "foo");
     ar1.AsyncWaitHandle.WaitOne();
     d.EndInvoke(ar1);
     Thread.Sleep(1000);
     Console.WriteLine("Main returns");
 }
 internal ListenManager(ClientEngine engine)
 {
     Engine = engine;
     listeners = new MonoTorrentCollection<PeerListener>();
     endCheckEncryptionCallback = ClientEngine.MainLoop.Wrap(EndCheckEncryption);
     handshakeReceivedCallback = (a, b, c) => ClientEngine.MainLoop.Queue(() => onPeerHandshakeReceived(a, b, c));
 }
Example #9
0
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset >= buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (offset + count > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            ReadAsyncResult ar = new ReadAsyncResult(callback, state);
            bool shouldInvokeWriter;
            if (!TryCompleteReadRequest(buffer, offset, count, ar, out shouldInvokeWriter))
            {
                if (shouldInvokeWriter)
                {
                    InvokeWriter();
                }
            }
            return ar;
        }
        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);
        }
Example #11
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);
            }
        }
		protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
		{
			SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);

			SoapWebClientAsyncResult ainfo = null;
			try
			{
				SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
				message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
				
				WebRequest request = GetRequestForMessage (uri, message);
				
				ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);
				ainfo.Message = message;
				ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);

				ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
			}
			catch (Exception ex)
			{
				if (ainfo != null)
					ainfo.SetCompleted (null, ex, false);
			}

			return ainfo;
		}
        /// <summary>
        /// This method will validate a property value in a <see cref="BaseModel"/> object asyncronously.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="value">The value to validate.</param>
        /// <param name="propertyName">The name of the property to validate.</param>
        /// <param name="callback">A <see cref="AsyncCallback"/> that will be called when the operation completes.</param>
        /// <param name="state">A user defined object providing state to the asycronous operation.</param>
        /// <returns>A <see cref="IAsyncResult"/> object representing the asyncronous operation.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static IAsyncResult BeginValidateProperty(BaseModel model, object value, string propertyName, AsyncCallback callback, object state)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            return new ValidatePropertyAsyncResult(CurrentValidator, model, value, propertyName, callback, state);
        }
        /// <summary>
        /// This method will validate a <see cref="BaseModel"/> asyncronously.  Also, if the children of the given
        /// model need to be validated at the same time, it can do that as well.
        /// </summary>
        /// <param name="target">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="validateChildren">If the chilren of the given model should be validated as well, supply true.</param>
        /// <param name="callback">A <see cref="AsyncCallback"/> that will be called when the operation completes.</param>
        /// <param name="state">A user defined object providing state to the asycronous operation.</param>
        /// <returns>A <see cref="IAsyncResult"/> object representing the asyncronous operation.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static IAsyncResult BeginValidateModel(BaseModel target, bool validateChildren, AsyncCallback callback, object state)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            return new ValidateModelAsyncResult(CurrentValidator, target, validateChildren, callback, state);
        }
Example #15
0
        protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
        {
            //string cultureName = RouteData.Values["culture"] as string;
            string cultureName = null;
            // Attempt to read the culture cookie from Request
            HttpCookie cultureCookie = Request.Cookies["_culture"];
            if (cultureCookie != null)
            {
                cultureName = cultureCookie.Value;
            }

            //if (cultureName == null)
            //    cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ? Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages

            // Validate culture name
            cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe

            //if (RouteData.Values["culture"] as string != cultureName)
            //{
            //    // Force a valid culture in the URL
            //    RouteData.Values["culture"] = cultureName.ToLowerInvariant(); // lower case too

            //    // Redirect user
            //    Response.RedirectToRoute(RouteData.Values);
            //}

            // Modify current thread's cultures
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            return base.BeginExecuteCore(callback, state);
        }
		/// <summary>
		/// Initiates an asynchronous call to the HTTP handler.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
		/// <param name="cb">The <see cref="T:System.AsyncCallback"/> to call when the asynchronous method call is complete. If <paramref name="cb"/> is null, the delegate is not called.</param>
		/// <param name="extraData">Any extra data needed to process the request.</param>
		/// <returns>
		/// An <see cref="T:System.IAsyncResult"/> that contains information about the status of the process.
		/// </returns>
		public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
		{
			this.httpContext = context;
			BeforeControllerProcess(context);

			try
			{
				controllerContext.Async.Callback = cb;
				controllerContext.Async.State = extraData;

				engineContext.Services.ExtensionManager.RaisePreProcessController(engineContext);

				return asyncController.BeginProcess(engineContext, controllerContext);
			}
			catch(Exception ex)
			{
				var response = context.Response;

				if (response.StatusCode == 200)
				{
					response.StatusCode = 500;
				}

				engineContext.LastException = ex;

				engineContext.Services.ExtensionManager.RaiseUnhandledError(engineContext);

				AfterControllerProcess();

				throw new MonoRailException("Error processing MonoRail request. Action " +
				                            controllerContext.Action + " on asyncController " + controllerContext.Name, ex);
			}
		}
Example #17
0
        // Allows creating a pre-completed result with less interlockeds.  Beware!  Constructor calls the callback.
        // If a derived class ever uses this and overloads Cleanup, this may need to change.
        internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack, object result)
        {
            if (result == DBNull.Value)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.AssertFormat("LazyAsyncResult#{0}::.ctor()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this));
                }
                Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor()|Result can't be set to DBNull - it's a special internal value.");
            }

            _asyncObject = myObject;
            _asyncState = myState;
            _asyncCallback = myCallBack;
            _result = result;
            _intCompleted = 1;

            if (_asyncCallback != null)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback");
                }
                _asyncCallback(this);
            }
            else if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke");
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor() (pre-completed)");
            }
        }
 public void SendEmailAsync(string EmailAddress, string subject, string body)
 {
     var msg = PrepareMessage(EmailAddress, subject, body);
     SendEmailDelegate sd = new SendEmailDelegate(_smtpClient.Send);
     AsyncCallback cb = new AsyncCallback(SendEmailResponse);
     sd.BeginInvoke(msg, cb, sd); 
 }        
        public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
        {
            BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
            ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);

            UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler

            UdpServer.JoinMulticastGroup(BroadcastServer.Address);

            UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);

            MaxClients = maxclients;

            Ip = IPAddress.Any;
            this.Port = port;

            listener = new TcpListener(Ip, Port);
            Clients = new List<ClientContext>(MaxClients);

            listener.Start();

            BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);

            this.TextStack = TextStack;
        }
Example #20
0
		public Listener(IPEndPoint ipep)
		{
			m_Accepted = new Queue<Socket>();
			m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot;

			m_Listener = Bind(ipep);

			if (m_Listener == null)
			{
				return;
			}

			DisplayListener();

#if NewAsyncSockets
			m_EventArgs = new SocketAsyncEventArgs();
			m_EventArgs.Completed += new EventHandler<SocketAsyncEventArgs>( Accept_Completion );
			Accept_Start();
            #else
			m_OnAccept = OnAccept;
			try
			{
				IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener);
			}
			catch (SocketException ex)
			{
				NetState.TraceException(ex);
			}
			catch (ObjectDisposedException)
			{ }
#endif
		}
Example #21
0
 public WaitForAll(AsyncCallback callbackWhenOver, object asyncState)
 {
     callbackResults = new Dictionary<string, IAsyncResult>();
     this.callbackWhenOver = callbackWhenOver;
     this.asyncState = asyncState;
     handle = new AutoResetEvent(false);
 }
        public static WebResponse GetResponseNoEx(this WebRequest req)
        {
            WebResponse result = null;
            ManualResetEvent responseReady = new ManualResetEvent(false);

            AsyncCallback callback = new AsyncCallback(ar =>
                {
                        //var request = (WebRequest)ar.AsyncState;
                        result = req.EndGetResponseNoEx(ar);
                        responseReady.Set();
                });

            var async = req.BeginGetResponse(callback, null);

            if (!async.IsCompleted)
            {
                //async.AsyncWaitHandle.WaitOne();
                // Not having thread affinity seems to work better with ManualResetEvent
                // Using AsyncWaitHandle.WaitOne() gave unpredictable results (in the
                // unit tests), when EndGetResponse would return null without any error
                // thrown
                responseReady.WaitOne();
                //async.AsyncWaitHandle.WaitOne();
            }

            return result;
        }
        /// <summary>
        /// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods.
        /// </summary>
        /// <remarks>
        /// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/> 
        /// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>.
        /// </remarks>
        public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
        {
            Debug.Assert(task != null, "task");

            var taskCompletionSource = new TaskCompletionSource<object>(state);
            task.ContinueWith(
                t =>
                {
                    if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else
                    {
                        taskCompletionSource.SetResult(null);
                    }

                    if (callback != null)
                    {
                         callback(taskCompletionSource.Task);
                    }
                },
                TaskScheduler.Default);

            return taskCompletionSource.Task;
        }
 protected override IAsyncResult OnBeginResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state)
 {
     return new CompletedAsyncResult<EndpointDiscoveryMetadata>(
         this.Match(resolveCriteria),
         callback,
         state);
 }
Example #25
0
	public IAsyncResult BeginAuthentication(AsyncCallback callback, Object asyncState)
	{
		// Go off authenticate
		AuthenticationDelegate ad = DoAuthentication; 
		
		return ad.BeginInvoke(callback, ad);
	}
Example #26
0
        public Listener( int port )
        {
            m_ThisPort = port;
            m_Disposed = false;
            m_Accepted = new Queue();
            m_OnAccept = new AsyncCallback( OnAccept );

            m_Listener = Bind( IPAddress.Any, port );

            try
            {
                IPHostEntry iphe = Dns.Resolve( Dns.GetHostName() );

                ArrayList list = new ArrayList();
                list.Add( IPAddress.Loopback );

                Console.WriteLine( "Address: {0}:{1}", IPAddress.Loopback, port );

                IPAddress[] ips = iphe.AddressList;

                for ( int i = 0; i < ips.Length; ++i )
                {
                    if ( !list.Contains( ips[i] ) )
                    {
                        list.Add( ips[i] );

                        Console.WriteLine( "Address: {0}:{1}", ips[i], port );
                    }
                }
            }
            catch
            {
            }
        }
 internal IAsyncResult BeginGetConnection(ServicePoint servicePoint, ContextAwareResult outerResult, AsyncCallback callback, object state)
 {
     IAsyncResult result = null;
     try
     {
         this.UpdateServicePoint(servicePoint);
         this.connection = new SmtpConnection(this, this.client, this.credentials, this.authenticationModules);
         this.connection.Timeout = this.timeout;
         if (Logging.On)
         {
             Logging.Associate(Logging.Web, this, this.connection);
         }
         if (this.EnableSsl)
         {
             this.connection.EnableSsl = true;
             this.connection.ClientCertificates = this.ClientCertificates;
         }
         result = this.connection.BeginGetConnection(servicePoint, outerResult, callback, state);
     }
     catch (Exception exception)
     {
         throw new SmtpException(SR.GetString("MailHostNotFound"), exception);
     }
     return result;
 }
Example #28
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var tcs = new TaskCompletionSource<object>();

            context.ApplicationInstance.CompleteRequest();
            var clientId = new Guid(context.Request["clientId"]);

            var jsons = new List<CommandMessage>();

            var bus = SheepJaxComet.PollingCommandBus;
            var obs = bus.GetObservable(clientId).Replay();
            var subscription = obs.Connect();
            obs.TakeUntil(Observable.Interval(LongPollTimeout))
                .TakeUntil(obs.Take(1).Delay(BatchInterval))
                .Subscribe(jsons.Add, context.AddError, ()=>
                    {
                        try
                        {
                            subscription.Dispose();
                            context.Response.Write("[" + string.Join(",", jsons.Select(x => x.Message)) + "]");
                            bus.Consumed(jsons.LastOrDefault());
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("SheepJax exception thrown while writing to long-polling connection", ex);
                        }
                        finally
                        {
                            tcs.SetResult(null);
                            cb(tcs.Task);
                        }
                    });

            return tcs.Task;
        }
        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);
            }
        }
 public IAsyncResult BeginSendRequest(DsmlRequestDocument request, AsyncCallback callback, object state)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     HttpWebRequest dsmlConnection = (HttpWebRequest) WebRequest.Create(((DsmlDirectoryIdentifier) base.directoryIdentifier).ServerUri);
     this.PrepareHttpWebRequest(dsmlConnection);
     StringBuilder buffer = new StringBuilder(0x400);
     this.BeginSOAPRequest(ref buffer);
     buffer.Append(request.ToXml().InnerXml);
     this.EndSOAPRequest(ref buffer);
     RequestState state2 = new RequestState {
         request = dsmlConnection,
         requestString = buffer.ToString()
     };
     DsmlAsyncResult key = new DsmlAsyncResult(callback, state) {
         resultObject = state2
     };
     if (request.Count > 0)
     {
         key.hasValidRequest = true;
     }
     state2.dsmlAsync = key;
     this.httpConnectionTable.Add(key, dsmlConnection);
     dsmlConnection.BeginGetRequestStream(new AsyncCallback(DsmlSoapHttpConnection.RequestStreamCallback), state2);
     return key;
 }