//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 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 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 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 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; }
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)); }
/// <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; }
// 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)"); } }
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 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 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; }
public WaitForAll(AsyncCallback callbackWhenOver, object asyncState) { callbackResults = new Dictionary<string, IAsyncResult>(); this.callbackWhenOver = callbackWhenOver; this.asyncState = asyncState; handle = new AutoResetEvent(false); }
protected override IAsyncResult OnBeginResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state) { return new CompletedAsyncResult<EndpointDiscoveryMetadata>( this.Match(resolveCriteria), 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); } }
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); } }
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 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 }
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; }
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); }
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 { } }
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; }
/// <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); }
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> /// Asynchronous reads are not supported a NotSupportedException is always thrown /// </summary> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset to start storing data at.</param> /// <param name="count">The number of bytes to read</param> /// <param name="callback">The async callback to use.</param> /// <param name="state">The state to use.</param> /// <returns>Returns an <see cref="IAsyncResult"/></returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported"); }
/// <summary> /// Asynchronous writes arent supported, a NotSupportedException is always thrown /// </summary> /// <param name="buffer">The buffer to write.</param> /// <param name="offset">The offset to begin writing at.</param> /// <param name="count">The number of bytes to write.</param> /// <param name="callback">The <see cref="AsyncCallback"/> to use.</param> /// <param name="state">The state object.</param> /// <returns>Returns an IAsyncResult.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("BeginWrite is not supported"); }
/// <summary> /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed. /// <example> /// textchangedeventhandler.BeginInvoke(sender, e, callback); /// </example> /// </summary> public static IAsyncResult BeginInvoke(this TextChangedEventHandler textchangedeventhandler, Object sender, TextChangedEventArgs e, AsyncCallback callback) { if (textchangedeventhandler == null) { throw new ArgumentNullException("textchangedeventhandler"); } return(textchangedeventhandler.BeginInvoke(sender, e, callback, null)); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { ReadDelegate r = new ReadDelegate(Read); return(r.BeginInvoke(buffer, offset, count, callback, state)); }
/// <summary> /// Initiates the asynchronous execution of the DescribeDimensionKeys operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDimensionKeys operation on AmazonPIClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDimensionKeys /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/DescribeDimensionKeys">REST API Reference for DescribeDimensionKeys Operation</seealso> public virtual IAsyncResult BeginDescribeDimensionKeys(DescribeDimensionKeysRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeDimensionKeysRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeDimensionKeysResponseUnmarshaller.Instance; return(BeginInvoke(request, options, callback, state)); }
public CometAsyncResult(HttpContext context, AsyncCallback callback, object asyncState) { this.callback = callback; this.context = context; this.asyncState = asyncState; }
protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) { var property = context.DataContext.GetProperties()[Salesforce_Marketing_Cloud_Scope.SalesForcePropertyTag]; var salesForceProperty = property.GetValue(context.DataContext) as SalesForceProperty; String _Search = Search.Get(context); var task = (new CmdRestAPI(salesForceProperty.AuthToken, salesForceProperty.ServiceURL, _Search)).ExecuteAsync(); var tcs = new TaskCompletionSource <CmdRestAPI>(state); task.ContinueWith(t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(t.Result); } if (callback != null) { callback(tcs.Task); } }); return(tcs.Task); }
/// <summary> /// Begins an asynchronous operation to clear pages from a page blob. /// </summary> /// <param name="startOffset">The offset at which to begin clearing pages, in bytes. The offset must be a multiple of 512.</param> /// <param name="length">The length of the data range to be cleared, in bytes. The length must be a multiple of 512.</param> /// <param name="options">An object that specifies any additional options for the request.</param> /// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param> /// <param name="state">A user-defined object that will be passed to the callback delegate.</param> /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns> public IAsyncResult BeginClearPages(long startOffset, long length, BlobRequestOptions options, AsyncCallback callback, object state) { var fullModifiers = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options); return(TaskImplHelper.BeginImplWithRetry( () => this.ClearPageImpl(startOffset, length, fullModifiers), fullModifiers.RetryPolicy, callback, state)); }
public static void RegisterTask(this AsyncManager asyncManager, Func <AsyncCallback, IAsyncResult> beginDelegate, Action <IAsyncResult> endDelegate) { if (asyncManager == null) { throw new ArgumentNullException("asyncManager"); } if (beginDelegate == null) { throw new ArgumentNullException("beginDelegate"); } if (endDelegate == null) { throw new ArgumentNullException("endDelegate"); } // need to wait to execute the callback until after BeginXxx() has completed object delegateExecutingLockObj = new object(); AsyncCallback callback = ar => { lock (delegateExecutingLockObj) { // this empty lock is required to synchronized with the beginDelegate call } if (!ar.CompletedSynchronously) { try { asyncManager.Sync(() => endDelegate(ar)); // called on different thread, so have to take application lock } catch { // Need to swallow exceptions, as otherwise unhandled exceptions on a ThreadPool thread // can bring down the entire worker process. } finally { asyncManager.OutstandingOperations.Decrement(); } } }; IAsyncResult asyncResult; asyncManager.OutstandingOperations.Increment(); try { lock (delegateExecutingLockObj) { asyncResult = beginDelegate(callback); } } catch { asyncManager.OutstandingOperations.Decrement(); throw; } if (asyncResult.CompletedSynchronously) { try { endDelegate(asyncResult); // call on same thread } finally { asyncManager.OutstandingOperations.Decrement(); } } }
/// <summary> /// To get transportion data /// </summary> /// <param name="callback"> delegate that references a method that is called when the asynchronous operation completes </param> /// <param name="asyncState">user-defined object can be used to pass application-specific state information to the method invoked when the asynchronous operation completes </param> public IAsyncResult BeginShippingScheduleResponse(AsyncCallback callback, object asyncState) { var meridianAsyncResult = new MeridianAsyncResult(OperationContext.Current, callback, asyncState); ThreadPool.QueueUserWorkItem(CompleteShippingScheduleResponseProcess, meridianAsyncResult); return meridianAsyncResult; }
/// <summary> /// To get transportion data /// </summary> /// <param name="callback"> delegate that references a method that is called when the asynchronous operation completes </param> /// <param name="asyncState">user-defined object can be used to pass application-specific state information to the method invoked when the asynchronous operation completes </param> public IAsyncResult BeginRequisition(AsyncCallback callback, object asyncState) { var meridianAsyncResult = new MeridianAsyncResult(OperationContext.Current, callback, asyncState); ThreadPool.QueueUserWorkItem(CompleteRequisitionProcess, meridianAsyncResult); return meridianAsyncResult; }
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { return(_originalInvoker.InvokeBegin(instance, inputs, callback, state)); }
/// <summary> /// Begins an asynchronous command execution. /// </summary> /// <param name="commandText">The command text.</param> /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param> /// <returns> /// An <see cref="System.IAsyncResult" /> that represents the asynchronous command execution, which could still be pending. /// </returns> /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception> /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception> public IAsyncResult BeginExecute(string commandText, AsyncCallback callback, object state) { this.CommandText = commandText; return(BeginExecute(callback, state)); }
public void BeginReceive(byte[] buf, int offset, int length, SocketFlags flags, AsyncCallback cb, object state) { lock (this) { if (!_shuttedDown_Receive) { _socket.BeginReceive(buf, offset, length, flags, cb, state); } } }
/// <summary> /// Initiates the asynchronous execution of the DescribeEventTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEventTypes operation on AmazonAWSHealthClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeEventTypes /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/health-2016-08-04/DescribeEventTypes">REST API Reference for DescribeEventTypes Operation</seealso> public IAsyncResult BeginDescribeEventTypes(DescribeEventTypesRequest request, AsyncCallback callback, object state) { var marshaller = new DescribeEventTypesRequestMarshaller(); var unmarshaller = DescribeEventTypesResponseUnmarshaller.Instance; return(BeginInvoke <DescribeEventTypesRequest>(request, marshaller, unmarshaller, callback, state)); }
/// <summary> /// Initiates the asynchronous execution of the GetResourceMetrics operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceMetrics operation on AmazonPIClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResourceMetrics /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/GetResourceMetrics">REST API Reference for GetResourceMetrics Operation</seealso> public virtual IAsyncResult BeginGetResourceMetrics(GetResourceMetricsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceMetricsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceMetricsResponseUnmarshaller.Instance; return(BeginInvoke(request, options, callback, state)); }
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 )); }
/// <summary> /// Begins an asynchronous command execution. /// </summary> /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param> /// <returns> /// An <see cref="System.IAsyncResult" /> that represents the asynchronous command execution, which could still be pending. /// </returns> /// <exception cref="System.InvalidOperationException">Asynchronous operation is already in progress.</exception> /// <exception cref="SshException">Invalid operation.</exception> /// <exception cref="System.ArgumentException">CommandText property is empty.</exception> /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception> /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception> /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception> /// <exception cref="ArgumentException">CommandText property is empty.</exception> public IAsyncResult BeginExecute(AsyncCallback callback) { return(this.BeginExecute(callback, null)); }
/// <summary> /// Begins an asynchronous operation to clear pages from a page blob. /// </summary> /// <param name="startOffset">The offset at which to begin clearing pages, in bytes. The offset must be a multiple of 512.</param> /// <param name="length">The length of the data range to be cleared, in bytes. The length must be a multiple of 512.</param> /// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param> /// <param name="state">A user-defined object that will be passed to the callback delegate.</param> /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns> public IAsyncResult BeginClearPages(long startOffset, long length, AsyncCallback callback, object state) { return(this.BeginClearPages(startOffset, length, null, callback, state)); }
public DeleteWorkflowOwnerAsyncResult(InstancePersistenceContext context, InstancePersistenceCommand command, SqlWorkflowInstanceStore store, SqlWorkflowInstanceStoreLock storeLock, Transaction currentTransaction, TimeSpan timeout, AsyncCallback callback, object state) : base(context, command, store, storeLock, currentTransaction, timeout, callback, state) { }
protected abstract IAsyncResult OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state);
/// <summary> /// Begins an asynchronous operation to return a collection of page ranges and their starting and ending bytes. /// </summary> /// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param> /// <param name="state">A user-defined object that will be passed to the callback delegate.</param> /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns> public IAsyncResult BeginGetPageRanges(AsyncCallback callback, object state) { return(this.BeginGetPageRanges(null, callback, state)); }
/// <summary> /// Begins an asynchronous operation to upload a blob from a stream. /// </summary> /// <param name="source">The data stream to upload.</param> /// <param name="options">An object that specifies any additional options for the request.</param> /// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param> /// <param name="state">A user-defined object that will be passed to the callback delegate.</param> /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns> /// <exception cref="NotSupportedException">This operation is not supported on objects of type <see cref="CloudPageBlob"/>.</exception> public override IAsyncResult BeginUploadFromStream(Stream source, BlobRequestOptions options, AsyncCallback callback, object state) { throw ThisCreationMethodNotSupportedException(); }
public IAsyncResult BeginAwardAchievement(string achievementId, AsyncCallback callback, Object state) { return(BeginAwardAchievement(achievementId, 100.0, callback, state)); }
private IAsyncResult BeginReceiveInternal(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(this._socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state)); }
public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state) { return(this.BeginReply(message, _defaultSendTimeout, callback, state)); }
// // Begin send on connected socket // public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state) => TaskToApm.Begin(SendAsync(datagram, bytes), requestCallback, state);
// // Begin sending on unconnected socket to named host // public IAsyncResult BeginSend(byte[] datagram, int bytes, SocketAddress endpoint, AsyncCallback requestCallback, object state) => TaskToApm.Begin(SendAsync(datagram, bytes, endpoint), requestCallback, state);
// // Begin receive on socket // public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state) { return(TaskToApm.Begin(ReceiveAsync(), requestCallback, state)); }
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) { FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor); Action continuation = null; BeginInvokeDelegate beginDelegate = delegate( AsyncCallback asyncCallback, object asyncState ) { try { AuthenticationContext authenticationContext = InvokeAuthenticationFilters( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor ); if (authenticationContext.Result != null) { // An authentication filter signaled that we should short-circuit the request. Let all // authentication filters contribute to an action result (to combine authentication // challenges). Then, run this action result. AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor, authenticationContext.Result ); continuation = () => InvokeActionResult( controllerContext, challengeContext.Result ?? authenticationContext.Result ); } else { AuthorizationContext authorizationContext = InvokeAuthorizationFilters( controllerContext, filterInfo.AuthorizationFilters, actionDescriptor ); if (authorizationContext.Result != null) { // An authorization filter signaled that we should short-circuit the request. Let all // authentication filters contribute to an action result (to combine authentication // challenges). Then, run this action result. AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor, authorizationContext.Result ); continuation = () => InvokeActionResult( controllerContext, challengeContext.Result ?? authorizationContext.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); // The action succeeded. Let all authentication filters contribute to an action // result (to combine authentication challenges; some authentication filters need // to do negotiation even on a successful result). Then, run this action result. AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor, postActionContext.Result ); InvokeActionResultWithFilters( controllerContext, filterInfo.ResultFilters, challengeContext.Result ?? 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)); } }
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; }
public IAsyncResult BeginAuthentication(AsyncCallback callback, Object asyncState) { // Go off authenticate AuthenticationDelegate ad = DoAuthentication; return ad.BeginInvoke(callback, ad); }
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; }