📄 rudpasyncresult.cs
字号:
namespace NCindy.Protocol.RUDP
{
using NCindy.Protocol.RUDP.Stack;
using System;
using System.Threading;
public class RUDPAsyncResult : IAsyncResult
{
private readonly AsyncCallback _asyncCallback;
private readonly object _asyncState;
private ManualResetEvent _asyncWaitHandle;
internal RUDPSocket _rudp;
private const int c_StateCompletedAsynchronously = 2;
private const int c_StateCompletedSynchronously = 1;
private const int c_StatePending = 0;
public bool ForceAsyncCall;
private int m_CompletedState;
public RUDPSocketError SocketError;
internal RUDPAsyncResult(RUDPSocket rudp, AsyncCallback callback, object state)
{
this._rudp = rudp;
this._asyncCallback = callback;
this._asyncState = state;
}
private void CompleteAsyncCall(object state)
{
try
{
this._asyncCallback(this);
}
catch (Exception exception)
{
RUDPStack.HandleException(exception, new object[0]);
}
}
internal void EndInvoke(bool canThrowException)
{
if (!this.IsCompleted)
{
this.AsyncWaitHandle.WaitOne();
this.AsyncWaitHandle.Close();
this._asyncWaitHandle = null;
}
if (canThrowException && (this.SocketError != RUDPSocketError.Success))
{
throw new RUDPSocketException(this.SocketError);
}
}
internal void SetAsCompleted(RUDPSocketError socketError, bool completedSynchronously)
{
this.SocketError = socketError;
if (Interlocked.Exchange(ref this.m_CompletedState, completedSynchronously ? 1 : 2) != 0)
{
throw new InvalidOperationException("You can set a result only once");
}
if (this._asyncWaitHandle != null)
{
this._asyncWaitHandle.Set();
}
if (this._asyncCallback != null)
{
if (!this.ForceAsyncCall)
{
try
{
this._asyncCallback(this);
}
catch (Exception exception)
{
RUDPStack.HandleException(exception, new object[0]);
}
}
else
{
ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(this.CompleteAsyncCall), null);
}
}
}
public object AsyncState
{
get
{
return this._asyncState;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (this._asyncWaitHandle == null)
{
bool initialState = this.IsCompleted;
ManualResetEvent event2 = new ManualResetEvent(initialState);
if (Interlocked.CompareExchange<ManualResetEvent>(ref this._asyncWaitHandle, event2, null) != null)
{
event2.Close();
}
else if (!initialState && this.IsCompleted)
{
this._asyncWaitHandle.Set();
}
}
return this._asyncWaitHandle;
}
}
public bool CompletedSynchronously
{
get
{
return (Thread.VolatileRead(ref this.m_CompletedState) == 1);
}
}
public bool IsCompleted
{
get
{
return (Thread.VolatileRead(ref this.m_CompletedState) != 0);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -