• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# AsyncCallback类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: LazyAsyncResult

        // 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)");
            }
        }
开发者ID:neris,项目名称:corefx,代码行数:37,代码来源:LazyAsyncResult.cs


示例17: SendEmailAsync

 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); 
 }        
开发者ID:Amit-khandelwal,项目名称:Amit_EmployeeFinder,代码行数:7,代码来源:EmailService.cs


示例18: ServerContext

        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;
        }
开发者ID:janis2013,项目名称:TextVerteilerServerDns,代码行数:25,代码来源:ServerContext.cs


示例19: WaitForAll

 public WaitForAll(AsyncCallback callbackWhenOver, object asyncState)
 {
     callbackResults = new Dictionary<string, IAsyncResult>();
     this.callbackWhenOver = callbackWhenOver;
     this.asyncState = asyncState;
     handle = new AutoResetEvent(false);
 }
开发者ID:npenin,项目名称:uss,代码行数:7,代码来源:WaitForAll.cs


示例20: GetResponseNoEx

        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;
        }
开发者ID:peterswallow,项目名称:fhir-net-api,代码行数:27,代码来源:WebRequestExtensions.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# AsyncContinuation类代码示例发布时间:2022-05-24
下一篇:
C# AsymmetricKeyParameter类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap