Asynchronous programming design pattern

后端 未结 4 1908
失恋的感觉
失恋的感觉 2021-02-10 23:29

I\'m working on a little technical framework for CF.NET and my question is, how should I code the asynchronous part? Read many things on MSDN but isn\'t clear for me.

So

4条回答
  •  无人共我
    2021-02-10 23:32

    You could use a delegate:

    public class A
    {
        public void Execute()
        {
            Thread.Sleep(1000 * 3);
        }
    }
    
    class Program
    {
        static void Main()
        {
            var a = new A();
            Action del = (() => a.Execute());
            var result = del.BeginInvoke(state =>
            {
                ((Action)state.AsyncState).EndInvoke(state);
                Console.WriteLine("finished");
            }, del);
            Console.ReadLine();
        }
    }
    

    UPDATE:

    As requested in the comments section here's a sample implementation:

    public class A
    {
        private Action _delegate;
        private AutoResetEvent _asyncActiveEvent;
    
        public IAsyncResult BeginExecute(AsyncCallback callback, object state)
        {
            _delegate = () => Execute();
            if (_asyncActiveEvent == null)
            {
                bool flag = false;
                try
                {
                    Monitor.Enter(this, ref flag);
                    if (_asyncActiveEvent == null)
                    {
                        _asyncActiveEvent = new AutoResetEvent(true);
                    }
                }
                finally
                {
                    if (flag)
                    {
                        Monitor.Exit(this);
                    }
                }
            }
            _asyncActiveEvent.WaitOne();
            return _delegate.BeginInvoke(callback, state);
        }
    
        public void EndExecute(IAsyncResult result)
        {
            try
            {
                _delegate.EndInvoke(result);
            }
            finally
            {
                _delegate = null;
                _asyncActiveEvent.Set();
            }
        }
    
        private void Execute()
        {
            Thread.Sleep(1000 * 3);
        }
    }
    
    class Program
    {
        static void Main()
        {
            A a = new A();
            a.BeginExecute(state =>
            {
                Console.WriteLine("finished");
                ((A)state.AsyncState).EndExecute(state);
            }, a);
            Console.ReadLine();
        }
    }
    

提交回复
热议问题