|
/// <summary>
/// 非同步請求對象
/// </summary>
public class AsyncResult : IAsyncResult
{
static readonly object lockObject = new object();
private ManualResetEvent completeEvent = null;
#region IAsyncResult 成員
/// <summary>
/// 初始化
/// </summary>
/// <param name="cb">回調方法</param>
/// <param name="asyncState">使用者狀態資料</param>
internal AsyncResult(AsyncCallback cb,object asyncState)
{
this.Callback = cb;
this.AsyncState = asyncState;
this.IsCompleted = false;
this.ParentResult = null;
this.Exception = null;
this.State = null;
}
/// <summary>
/// 擷取使用者狀態資料
/// </summary>
public object AsyncState
{
get;
internal set;
}
/// <summary>
/// 擷取或設定自訂狀態資料
/// </summary>
public object State
{
get;
set;
}
/// <summary>
/// 非同步等待控制代碼
/// </summary>
public System.Threading.WaitHandle AsyncWaitHandle
{
get
{
lock (lockObject)
{
if (this.completeEvent == null)
this.completeEvent = new ManualResetEvent(false);
return this.completeEvent;
}
}
}
/// <summary>
/// 完成同上
/// </summary>
public bool CompletedSynchronously
{
get { return false; }
}
/// <summary>
/// 是否已完成
/// </summary>
public bool IsCompleted
{
get;
private set;
}
#endregion
/// <summary>
/// 父級Result,如果存在
/// </summary>
public IAsyncResult ParentResult { get; set; }
/// <summary>
/// 擷取非同步完成調用
/// </summary>
public AsyncCallback Callback
{
get;
internal set;
}
/// <summary>
/// 擷取或設定非同步過程中產生的異常
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Completes the request.
/// </summary>
public void Completed()
{
this.IsCompleted = true;
lock (lockObject)
{
if (this.completeEvent != null)
this.completeEvent.Set();
}
if (this.Callback != null)
this.Callback(this);
}
/// <summary>
/// Completes the request.
/// </summary>
public void Completed(Exception ex) {
this.Exception = ex;
this.Completed();
}
} |