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


C# AsyncCallback.BeginInvoke方法代码示例

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


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

示例1: BeginRead

 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback,
                                        object state)
 {
     _event.Reset();
     AsyncRes res = new AsyncRes(buffer, offset, count);
     callback.BeginInvoke(res, null, state);
     return res;
 }
开发者ID:kf6kjg,项目名称:halcyon,代码行数:8,代码来源:MyStream.cs

示例2: BeginWrite

		BeginWrite (byte [] buffer, int offset, int count, AsyncCallback callback, object state)
		{
			if (!CanWrite)
				throw new NotSupportedException ("This stream does not support writing");
	
			// Creating a class derived from Stream that doesn't override BeginWrite
			// shows that it actually calls Write and does everything synchronously except
			// when invoking the callback, which is done from the ThreadPool.
			// Just put this in the Write override:
			// 	Console.WriteLine ("Write");
			// 	Console.WriteLine (Environment.StackTrace);
			//	Thread.Sleep (10000);

			StreamAsyncResult result = new StreamAsyncResult (state);
			try {
				Write (buffer, offset, count);
				result.SetComplete (null);
			} catch (Exception e) {
				result.SetComplete (e);
			}

			if (callback != null)
				callback.BeginInvoke (result, null, null);

			return result;
		}
开发者ID:stabbylambda,项目名称:mono,代码行数:26,代码来源:Stream.cs

示例3: BeginWrite

        /// <include file='doc\Stream.uex' path='docs/doc[@for="Stream.BeginWrite"]/*' />
        public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
        {
            if (!CanWrite) __Error.WriteNotSupported();

            // To avoid a race with a stream's position pointer & generating race 
            // conditions with internal buffer indexes in our own streams that 
            // don't natively support async IO operations when there are multiple 
            // async requests outstanding, we will block the application's main
            // thread and do the IO synchronously.  
            SynchronousAsyncResult asyncResult = new SynchronousAsyncResult(state, true);
            try {
                Write(buffer, offset, count);
                asyncResult._isCompleted = true;
                asyncResult._waitHandle.Set();
            }
            catch (IOException e) {
                asyncResult._exception = e;
            }
            
            if (callback != null)
                callback.BeginInvoke(asyncResult, null, null);

            return asyncResult;
        }
开发者ID:ArildF,项目名称:masters,代码行数:25,代码来源:stream.cs

示例4: Send

 /// <summary>
 /// 发送数据到指定终端
 /// </summary>
 /// <param name="sendObj"></param>
 /// <param name="_sendCallback">发送后的回调函数</param>
 public void Send(SendClientObject sendObj,AsyncCallback _sendCallback)
 {
     lock (sendObj.stateObject.sendLockObj)
     {
         var data = sendObj.txData.GetData();
         try
         {
             sendObj.stateObject.workSocket.BeginSend(data, 0, data.Length, SocketFlags.None, p =>
             {
                 try
                 {
                     sendObj.stateObject.workSocket.EndSend(p);
                     sendObj.IsSendOK = true;
                 }
                 catch(Exception ex) {
                     sendObj.IsSendOK = false;
                     sendObj.ErrMsg = ex.Message;
                     if (ClientErrorEvent != null)
                     {
                         ClientErrorEvent.BeginInvoke(sendObj.stateObject, ex.Message, null, null);
                     }
                 }
                 if (_sendCallback != null)
                 {
                     _sendCallback.BeginInvoke((IAsyncResult)sendObj, null, null);
                 }
             }, sendObj);
         }
         catch (Exception ex)
         {
             sendObj.IsSendOK = false;
             sendObj.ErrMsg = ex.Message;
             if (ClientErrorEvent != null)
             {
                 ClientErrorEvent.BeginInvoke(sendObj.stateObject, ex.Message, null, null);
             }
             if (_sendCallback != null)
             {
                 _sendCallback.BeginInvoke((IAsyncResult)sendObj, null, null);
             }
         }
     }
 }
开发者ID:zhanzi,项目名称:slzrsz,代码行数:48,代码来源:MyServer.cs

示例5: BeginPagesListRequest

		private IAsyncResult BeginPagesListRequest(object sender, EventArgs e, AsyncCallback cb, object state) {
			IAsyncResult ar = null;
			List<string> pages = new List<string>();
			try {
				if(lstWiki.SelectedValue.ToUpperInvariant() == "MEDIA") {
					//Download all namespaces
					string url = txtWikiUrl.Text + "?title=Special:Allpages&namespace=0";

					List<string> namespaces = GetNamespaces(PageRequest(url));

					//Download list of pages
					for(int k = 0; k < namespaces.Count; k = k + 2) {
						string pageText = PageRequest(txtWikiUrl.Text + "?title=Special:Allpages&namespace=" + namespaces[k]);

						Regex allPagesTable = new Regex(@"(?<=(\<table\ class=\'allpageslist\'([^>])*?)\>)(.|\s)+?(?=(\<\/table\>))");
						Match table = allPagesTable.Match(pageText);
						if(table.Success) {
							string tableStr = table.Value;
							Regex allPagesData = new Regex(@"(?<=(\<a([^>])*?)\>)(.|\s)+?(?=(\<\/a\>))");
							Match data = allPagesData.Match(tableStr);
							int i = 2;
							while(data.Success) {
								i++;
								if(i == 3) {
									pages.AddRange(PartialList(PageRequest(txtWikiUrl.Text + "?title=Special:Allpages&from=" + data.Value + "&namespace=" + namespaces[k]), namespaces[k + 1]));
									i = 0;
								}
								tableStr = tableStr.Substring(data.Index + data.Length + 5);
								data = allPagesData.Match(tableStr);
							}
						}
						else
							pages.AddRange(PartialList(pageText, namespaces[k + 1]));
					}
				}
				else {
					string pageText = null;
					if(txtWikiUrl.Text.EndsWith("/")) pageText = PageRequest(txtWikiUrl.Text + @"search.aspx?search=&namespace=%5BAll%5D");
					else pageText = PageRequest(txtWikiUrl.Text + @"/search.aspx?search=&namespace=%5BAll%5D");
					Regex pageTitle = new Regex(@"<div class='searchHitHead'>(.|\s)+?</div>");
					Match match = pageTitle.Match(pageText);
					while(match.Success) {
						pages.Add(match.Value.Substring(37, match.Value.IndexOf('"', 37) - 37));
						match = pageTitle.Match(pageText, match.Index + match.Length - 1);
					}
				}
				pageList.Items.Clear();

				for(int i = 0; i < pages.Count; i++) {
					pageList.Items.Add(new ListItem(pages[i], pages[i]));
					pageList.Items[i].Selected = true;
				}
				if(pages.Count > 1000) {
					pageList.Visible = false;
					pageList_div.Visible = false;
					lblPageList.Text = "Too many pages. Click Translate button to import whole wiki.";
				}
				else {
					pageList.Visible = true;
					pageList_div.Visible = true;
					lblPageList.Text = "To exclude pages, uselect them";
				}
			}
			catch(WebException) {
				pageList.Visible = false;
				pageList_div.Visible = false;
				btnTranslateAll.Visible = false;
				lblPageList.Text = "Web Exception";
			}

			return cb.BeginInvoke(ar, cb, null);
		}
开发者ID:mono,项目名称:ScrewTurnWiki,代码行数:72,代码来源:Import.aspx.cs

示例6: PageDownload

		private IAsyncResult PageDownload(object sender, EventArgs e, AsyncCallback ac, object state) {
			IAsyncResult ar = null;
			return ac.BeginInvoke(ar, ac, null);
		}
开发者ID:mono,项目名称:ScrewTurnWiki,代码行数:4,代码来源:Import.aspx.cs

示例7: StartReceivingData

        private void StartReceivingData()
        {
            fLastDataAction = DateTime.Now.Ticks;

            fActive = true;
            fMyListener.MyExtasysTCPServer.OnClientConnect(this);
            try
            {
                fConnection.BeginReceive(fReadBuffer, 0, fReadBufferSize, SocketFlags.None, new AsyncCallback(StreamReceiver), null);
                if (fConnection.SendTimeout > 0)
                {
                    AsyncCallback call = new AsyncCallback(CheckConnectionTimeOut);
                    call.BeginInvoke(null, call, null);
                }
            }
            catch (ArgumentNullException argumentNullException) // Buffer is a null reference. 
            {
                DisconnectMe();
            }
            catch (SocketException socketException) // An error occurred when attempting to access the socket.
            {
                DisconnectMe();
            }
            catch (ObjectDisposedException objectDisposedException) // Socket has been closed.
            {
                DisconnectMe();
            }
            catch (ArgumentOutOfRangeException argumentOutOfRangeException) // Offset is less than 0.
            {
                DisconnectMe();
            }
            catch (Exception ex)
            {
            }
        }
开发者ID:thiagonego,项目名称:extasys,代码行数:35,代码来源:TCPClientConnection.cs

示例8: ListenConfirm

        /// <summary>
        /// This method is called after the transport-server handshake is confirmed. This method starts the listening process.
        /// </summary>
        /// <param name="context">The transport context.</param>
        /// <param name="job">The job.</param>
        /// <param name="Data">The request/response data.</param>
        /// <returns>Returns false is the listening process has started successfully.</returns>
        public override bool ListenConfirm(TransportContext context, SecurityManagerJob job, RQRSContract<TransportCommandRequest, TransportCommandResponse> Data)
        {
            TransportContextTCPIP tcpContext = context as TransportContextTCPIP;
            if (tcpContext == null)
            {
                Data.Response.Status = CH.HTTPCodes.ServiceUnavailable_503;
                return true;
            }

            Uri location = tcpContext.Location;
            //Ok, validate the IP address
            IPAddress address;
            if (!IPAddress.TryParse(location.Host, out address))
            {
                if (location.Host.ToLowerInvariant() != "localhost")
                {
                    Data.Response.Status = CH.HTTPCodes.BadRequest_400;
                    Data.Response.Substatus = string.Format("Location '{0}' is not a valid listening address.", location.Host);
                    return true;
                }
                address = IPAddress.Loopback;
            }

            IPEndPoint EndPoint = new IPEndPoint(address, location.Port);

            try
            {
                Socket listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //We need to start listening on the appropriate ports and IP addresses
                listeningSocket.Bind(EndPoint);

                //Start the socket listening, the cnLISTENQUEUE is the number of items we allow
                //in the connection queue
                listeningSocket.Listen(tcpContext.ListenerQueueLength);

                //tcpContext.LocalEndPoint = EndPoint;
                tcpContext.ActiveSocket = listeningSocket;

                //Ok, we need to shunt off the listening duties to another thread so that we can returns to
                //the server on this thread.


                AsyncCallback startListening = new AsyncCallback(tcpContext.ListenerStart);

                startListening.BeginInvoke(null, null, null);

                Data.Response.Status = CH.HTTPCodes.OK_200;
                return false;

            }
            catch (SocketException socex)
            {
                Data.Response.Status = CH.HTTPCodes.BadRequest_400;
                Data.Response.Substatus = string.Format("The socket threw an exception {0}:{1} ({2})", socex.ErrorCode, socex.SocketErrorCode, socex.Message);
                return true;
            }
            catch (ObjectDisposedException obex)
            {
                Data.Response.Status = CH.HTTPCodes.InternalServerError_500;
                Data.Response.Substatus = string.Format("The socket threw an object disposed exception {0}", obex.Message);
                return true;
            }
            catch (Exception ex)
            {
                Data.Response.Status = CH.HTTPCodes.InternalServerError_500;
                Data.Response.Substatus = string.Format("An unhandeled exception was caught {0}/{1}", ex.GetType().ToString(), ex.Message);
                return true;
            }

        }
开发者ID:mbmccormick,项目名称:Ximura,代码行数:78,代码来源:ListenTCPIPTransportState.cs


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