当前位置: 首页>>代码示例>>C#>>正文


C# AsyncCallback类代码示例

本文整理汇总了C#中AsyncCallback的典型用法代码示例。如果您正苦于以下问题:C# AsyncCallback类的具体用法?C# AsyncCallback怎么用?C# AsyncCallback使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


AsyncCallback类属于命名空间,在下文中一共展示了AsyncCallback类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BeginTryCommand

        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);
            }
        }
开发者ID:40a,项目名称:PowerShell,代码行数:29,代码来源:FileInstanceStore.cs

示例2: NonEntityOperationResult

 internal NonEntityOperationResult(object source, HttpWebRequest request, AsyncCallback callback, object state)
 {
   this.source = source;
   this.request = request;
   this.userCallback = callback;
   this.userState = state;
 }
开发者ID:modulexcite,项目名称:SilverlightWpfContrib,代码行数:7,代码来源:NonEntityOperationResult.cs

示例3: BeginOpenRead

        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;
        }
开发者ID:huoxudong125,项目名称:azure-sdk-for-net,代码行数:29,代码来源:CloudBlockBlob.cs

示例4: BeginTryReceiveRequest

 public IAsyncResult BeginTryReceiveRequest(
     TimeSpan timeout, AsyncCallback callback, 
     object state)
 {
     ValidateTimeSpan(timeout);
     return this.requestQueue.BeginDequeue(timeout, callback, state);
 }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:7,代码来源:HttpCookieReplySessionChannel.cs

示例5: Main

    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;
    }
开发者ID:robertmichaelwalsh,项目名称:CSharpFrontEnd,代码行数:31,代码来源:async_read.cs

示例6: BeginDownloadXml

        //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());

        }
开发者ID:GuiBGP,项目名称:qdfeed,代码行数:8,代码来源:FileSystemFeedFactory.cs

示例7: Main

 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");
 }
开发者ID:robertmichaelwalsh,项目名称:CSharpFrontEnd,代码行数:25,代码来源:delegate-async-exit.cs

示例8: BeginRead

        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;
        }
开发者ID:pusp,项目名称:o2platform,代码行数:26,代码来源:AdapterStream.cs

示例9: BeginExecute

        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);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:60,代码来源:ReflectedAsyncActionDescriptor.cs

示例10: BeginProcessRequest

        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);
            }
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:30,代码来源:MvcHttpHandler.cs

示例11: BeginInvoke

		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;
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:26,代码来源:SoapHttpClientProtocol.cs

示例12: BeginValidateProperty

        /// <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);
        }
开发者ID:KCL5South,项目名称:PTPDevelopmentLibrary,代码行数:17,代码来源:Validator.cs

示例13: BeginValidateModel

        /// <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);
        }
开发者ID:KCL5South,项目名称:PTPDevelopmentLibrary,代码行数:17,代码来源:Validator.cs

示例14: BeginExecuteCore

        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);
        }
开发者ID:sbudihar,项目名称:SIRIUSrepo,代码行数:32,代码来源:BaseController.cs

示例15: BeginProcessRequest

		/// <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);
			}
		}
开发者ID:smoothdeveloper,项目名称:Castle.MonoRail,代码行数:42,代码来源:BaseAsyncHttpHandler.cs


注:本文中的AsyncCallback类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。