IAsyncResult

C# IAsyncResult 接口实现,封装一个异步实现的功能

如下例子:

 public class AsyncDoWork : IAsyncResult
    {
        private object m_AsyncState;
        private AsyncCallback m_CompleteAsyncCall;
        private bool m_isComplete;
        private object[] Paras;
        public object Result { get; private set; }
        public Exception Error { get; private set; }
       
        public bool IsCompleted
        {
            get
            {
                return m_isComplete;
            }
            private set { }
        }
        public AsyncDoWork()
        {
           
        }
        public AsyncDoWork(object asyncState)
        {
            m_AsyncState = asyncState;
        }
        public void BeginDoWork(Delegate method, AsyncCallback callback, params object[] paras)
        {
            m_CompleteAsyncCall = callback;
            (new Action((obj) =>
            {
                try
                {
                    if (method != null)
                    {
                        Result = method.DynamicInvoke(obj);
                        m_isComplete = true;
                    }

                }
                catch (Exception ex)
                {
                    m_isComplete = false;
                    Error = ex;
                    System.Diagnostics.Debug.Write(ex.Message);
                }
            })).BeginInvoke(paras, new AsyncCallback(Callback), paras);
        }

        private void Callback(IAsyncResult ar)
        {
            this.Paras = ar.AsyncState as object[];
            if (m_CompleteAsyncCall != null)
            {
                m_CompleteAsyncCall.BeginInvoke(this, null, ar.AsyncState);
            }

        }
        public object AsyncState { get { return m_AsyncState; } private set { } }

        public WaitHandle AsyncWaitHandle { get; private set; }

        public bool CompletedSynchronously { get; private set; }

       
    }

 

使用例子:

 AsyncDoWork sc = new AsyncDoWork(createdObject);
                                sc.BeginDoWork(delegate, new AsyncCallback(Callback), item);

 

 

 

 

你可能感兴趣的:(C#)