AsyncResult 自定义 IAsyncResult 类

    /// <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();
        }
    }

此条目发表在.net分类目录。将固定链接加入收藏夹。