本文整理汇总了C#中IAsyncResult类的典型用法代码示例。如果您正苦于以下问题:C# IAsyncResult类的具体用法?C# IAsyncResult怎么用?C# IAsyncResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
IAsyncResult类属于命名空间,在下文中一共展示了IAsyncResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ResponseCallback
private void ResponseCallback(IAsyncResult result)
{
var state = (List<object>) result.AsyncState;
var googleRequest = (GooglePlaceSearchRequest) state[1];
if (result.IsCompleted)
{
try
{
var request = (HttpWebRequest)state[0];
var response = (HttpWebResponse)request.EndGetResponse(result);
var responseStream = response.GetResponseStream();
var serializer = new DataContractJsonSerializer(typeof(GooglePlaceSearchResponse));
var googleSearchResponse = (GooglePlaceSearchResponse)serializer.ReadObject(responseStream);
if (googleSearchResponse.Status == GoogleMapsSearchStatus.OK)
SearchForPlacesAsyncCompleted(googleSearchResponse, googleRequest);
else if (googleSearchResponse.Status == GoogleMapsSearchStatus.ZERO_RESULTS)
SearchForPlacesAsyncNotFound(googleSearchResponse, googleRequest);
} catch(Exception e)
{
if (SearchForPlacesAsyncFailed!= null)
SearchForPlacesAsyncFailed(e.Message, e);
}
} else
{
if (SearchForPlacesAsyncFailed != null)
SearchForPlacesAsyncFailed("For some reason request is not completed", null);
}
}
示例2: RecieveCallback
protected override void RecieveCallback(IAsyncResult Result)
{
DatagramState Dstate = (DatagramState)Result.AsyncState;
int bytes = 0;
Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
S.Bind(new IPEndPoint(IPAddress.Any, 0));
Socket past = Dstate.ClientSocket;
Dstate.ClientSocket = S;
try
{
bytes = past.EndReceiveFrom(Result, ref Dstate.EndPoint);
}
catch (Exception e)
{
Next.Set();
Send("Respect the buffer size which is " + DatagramState.BufferSize.ToString(), Dstate);
return;
}
if (bytes>0)
{
string content = "";
Dstate.MsgBuilder.Append(Encoding.ASCII.GetString(Dstate.Buffer, 0, bytes));
content = Dstate.MsgBuilder.ToString();
Next.Set();
try
{
string r = Calculate(content).ToString();
Send(r, Dstate);
}
catch (Exception e)
{
Send(e.Message, Dstate);
}
}
}
示例3: AsyncCallback
/// <summary>
/// 回调委托
/// </summary>
/// <param name="ar">The ar.</param>
/// Author : 俞立钢
/// Company : 绍兴标点电子技术有限公司
/// Created : 2014-10-15 16:55:37
private void AsyncCallback(IAsyncResult ar)
{
if (ar.IsCompleted)
{
HideProgress();
}
}
示例4: OnReceive
void OnReceive(IAsyncResult result)
{
try
{
if (result.IsCompleted)
{
int bytesRead = socket.EndReceive(result);
if (bytesRead > 0)
{
byte[] read = new byte[bytesRead];
Array.Copy(buffer, 0, read, 0, bytesRead);
readHandler(this, read);
Begin(socket, readHandler, errorHandler);
}
else
{
// Disconnect
}
}
}
catch (Exception e)
{
if (errorHandler != null)
{
errorHandler(this, e);
}
}
}
示例5: ReadCallback
private void ReadCallback(IAsyncResult result)
{
try
{
if (this._isClosed)
{
this._clientSocket.Close();
return;
}
var networkStream = this._clientSocket.GetStream();
var read = networkStream.EndRead(result);
if (read == 0)
{
this._networkStream.Close();
this._clientSocket.Close();
return;
}
var buffer = (byte[]) result.AsyncState;
var data = Constants.Encoding.GetString(buffer, 0, read);
this.DataReceived?.Invoke(((IPEndPoint) this._clientSocket.Client.RemoteEndPoint).Address, data);
this.WaitForRequest();
}
catch (Exception ex)
{
Debug.WriteLine("Error: "+ex.Message);
}
}
示例6: ReadCallback
private void ReadCallback(IAsyncResult result)
{
NetworkStream networkStream = _clientSocket.GetStream();
try
{
int read = networkStream.EndRead(result);
if (read == 0)
{
_networkStream.Close();
_clientSocket.Close();
return;
}
byte[] buffer = result.AsyncState as byte[];
string data = Encoding.Default.GetString(buffer, 0, read);
handler.OnClientRead(_clientSocket, data);
}
catch (Exception ex)
{
throw;
}
this.WaitForRequest();
}
示例7: EndReceive
public IBrokeredMessage EndReceive(IAsyncResult result) {
var msg = client.EndReceive(result);
if (msg != null) {
return new BrokeredMessageWrapper(msg);
}
return null;
}
示例8: EndCommit
public void EndCommit (IAsyncResult ar)
{
if (ar != this)
throw new ArgumentException ("The IAsyncResult parameter must be the same parameter as returned by BeginCommit.", "asyncResult");
EndCommitInternal (asyncResult);
}
示例9: EndCheckEncryption
private void EndCheckEncryption(IAsyncResult result)
{
var id = (PeerId) result.AsyncState;
try
{
byte[] initialData;
EncryptorFactory.EndCheckEncryption(result, out initialData);
if (initialData != null && initialData.Length == HandshakeMessage.HandshakeLength)
{
var message = new HandshakeMessage();
message.Decode(initialData, 0, initialData.Length);
handleHandshake(id, message);
}
else if (initialData.Length > 0)
{
throw new Exception("Argh. I can't handle this scenario. It also shouldn't happen. Ever.");
}
else
{
PeerIO.EnqueueReceiveHandshake(id.Connection, id.Decryptor, handshakeReceivedCallback, id);
}
}
catch
{
id.Connection.Dispose();
}
}
示例10: AcceptCallback
/// <summary>
/// AcceptCallback是回调函数
/// </summary>
/// <param name="ar"></param>
public static void AcceptCallback(IAsyncResult ar)
{
// 接收连接后,按照前面的定义会执行该函数,首先就是让主线程继续往下执行
allDone.Set();
count++;
Console.WriteLine("连接已经建立");
try
{
//将接收的连接传递进来
Socket listener = (Socket)ar.AsyncState;
//调用EndAccept方法表示连接已经建立,建立的连接就是该方法的返回的对象
Socket handler = listener.EndAccept(ar);
//保存当前会话的Socket信息
StateObject state = new StateObject();
state.socket = handler;
//这里又出现了类似的定义。可以看出,BeginReceive函数的参数和同步里面Receive函数的参数前面是相同的
//只是后面多出了两个:定义在BeginReceive函数执行完毕以后所要执行的操作
//这里定义的是ReadCallback函数
handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
_iLog.Error(ex.Message);
}
}
示例11: OnAccept
private void OnAccept(IAsyncResult ar)
{
try
{
Socket clientSocket;
try
{
clientSocket = serverSocket.EndAccept(ar);
}
catch (ObjectDisposedException)
{
return;
}
// Once the client connects then start receiving the commands from it
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(OnReceive), clientSocket);
// Start listening for more clients
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
}
catch (SocketException)
{
}
catch (Exception ex)
{
PodcasterUtilities.KLIKException(ex);
}
}
示例12: EndGetHostAddress
private void EndGetHostAddress(IAsyncResult asyncResult)
{
var state = (State) asyncResult.AsyncState;
try
{
var addresses = Dns.EndGetHostAddresses(asyncResult);
var endPoint = new IPEndPoint(addresses[0], 123);
var socket = new UdpClient();
socket.Connect(endPoint);
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
var sntpData = new byte[SntpDataLength];
sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)
var newState = new State(socket, endPoint, state.GetTime, state.Failure);
var result = socket.BeginSend(sntpData, sntpData.Length, EndSend, newState);
RegisterWaitForTimeout(newState, result);
}
catch (Exception)
{
// retry, recursion stops at the end of the hosts
BeginGetDate(state.GetTime, state.Failure);
}
}
示例13: ReadCallback
public static void ReadCallback(IAsyncResult ar)
{
// Retrieve the state object and the handler socket from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = 0;
try
{
bytesRead = handler.EndReceive(ar);
}
catch (Exception e)
{
Console.Write(e);
}
//int bytesRead = state.buffer.Length;
if (bytesRead > 0)
{
string clientMsg = WebSocket.AnalyticData(state.buffer, bytesRead);
Console.WriteLine("接受到客户端数据:" + clientMsg);
Send(handler, clientMsg);
//接收下一条消息(因为这是一个递归的调用,所以这样就可以一直接收消息了)
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
//JavaScriptSerializer js = new JavaScriptSerializer();
//反序列化前台传过来的JSON字符串,变为ClientInfo对象
//ClientInfo clientInfo = js.Deserialize<ClientInfo>(clientMsg);
// if (clientInfo != null)
}
}
示例14: WaitForConnectionCallBack
private void WaitForConnectionCallBack(IAsyncResult iar)
{
try
{
// Get the pipe
NamedPipeServerStream pipeServer = (NamedPipeServerStream) iar.AsyncState;
// End waiting for the connection
pipeServer.EndWaitForConnection(iar);
StreamReader sr = new StreamReader(pipeServer);
StreamWriter sw = new StreamWriter(pipeServer);
var response = ProccesQueries(sr.ReadLine());
sw.WriteLine(response);
sw.Flush();
pipeServer.WaitForPipeDrain();
// Kill original sever and create new wait server
pipeServer.Disconnect();
pipeServer.Close();
pipeServer = null;
pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);
// Recursively wait for the connection again and again....
pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, pipeServer);
}
catch (Exception e)
{
Log.Debug("Pipe server error", e);
}
}
示例15: OnReceive
// Called when we receive data from the client
private void OnReceive(IAsyncResult res)
{
try
{
m_received += m_connection.EndReceive(res);
// if we haven't gotten enough for a full request yet, receive again
if (m_received < s_policyRequestString.Length)
{
m_connection.BeginReceive(m_buffer, m_received, s_policyRequestString.Length - m_received, SocketFlags.None, new AsyncCallback(OnReceive), null);
return;
}
// make sure the request is valid
string request = System.Text.Encoding.UTF8.GetString(m_buffer, 0, m_received);
if (StringComparer.InvariantCultureIgnoreCase.Compare(request, s_policyRequestString) != 0)
{
m_connection.Close();
return;
}
// send the policy
m_connection.BeginSend(m_policy, 0, m_policy.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
}
catch (SocketException)
{
m_connection.Close();
}
}