一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

AsyncResult 自定义 IAsyncResult 类

时间:2013-12-28 编辑:简简单单 来源:一聚教程网

 代码如下 复制代码

 ///


    /// 异步请求对象
    ///

    public class AsyncResult : IAsyncResult
    {
        static readonly object lockObject = new object();
        private ManualResetEvent completeEvent = null;
       
        #region IAsyncResult 成员

        ///


        /// 初始化
        ///

        /// 回调方法
        /// 用户状态数据
        internal AsyncResult(AsyncCallback cb,object asyncState)
        {
            this.Callback = cb;
            this.AsyncState = asyncState;
            this.IsCompleted = false;
            this.ParentResult = null;
            this.Exception = null;
            this.State = null;
        }

        ///


        /// 获取用户状态数据
        ///

        public object AsyncState
        {
            get;
            internal set;
        }

        ///


        /// 获取或设置自定义状态数据
        ///

        public object State
        {
            get;
            set;
        }

        ///


        /// 异步等待句柄
        ///

        public System.Threading.WaitHandle AsyncWaitHandle
        {
            get
            {
                lock (lockObject)
                {
                    if (this.completeEvent == null)
                        this.completeEvent = new ManualResetEvent(false);

                    return this.completeEvent;
                }
            }
        }

        ///


        /// 完成同上
        ///

        public bool CompletedSynchronously
        {
            get { return false; }
        }

        ///


        /// 是否已完成
        ///

        public bool IsCompleted
        {
            get;
            private set;
        }

        #endregion


        ///


        /// 父级Result,如果存在
        ///

        public IAsyncResult ParentResult { get; set; }
       
        ///
        /// 获取异步完成调用
        ///

        public AsyncCallback Callback
        {
            get;
            internal set;
        }


        ///


        /// 获取或设置异步过程中产生的异常
        ///

        public Exception Exception { get; set; }

        ///


        /// Completes the request.
        ///

        public void Completed()
        {
            this.IsCompleted = true;
            lock (lockObject)
            {
                if (this.completeEvent != null)
                    this.completeEvent.Set();
            }

            if (this.Callback != null)
                this.Callback(this);
        }

        ///


        /// Completes the request.
        ///

        public void Completed(Exception ex) {
            this.Exception = ex;
            this.Completed();
        }
    }

热门栏目