Asynchronous programming design pattern

混江龙づ霸主 提交于 2020-01-01 03:48:25

问题


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, here is the code :

public class A
{
    public IAsyncResult BeginExecute(AsyncCallback callback)
    {
        // What should I put here ?
    }

    public void EndExecute()
    {
        // What should I put here ?
    }

    public void Execute()
    {
        Thread.Sleep(1000 * 10);
    }
}

If someone can help me...

Thanks !


回答1:


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



回答2:


You don't need to do anything special, cause the caller should call you method async,

He define a new delegate pointing to you method, and use the .net to call your method asynchronously.




回答3:


On BeginExecute you have to start the asynchronous operation (possibly start execute in a separate thread) and return as quick as possible. Execute has to call the AsyncCallback at the end of all operations so that who use the async operation gets aware and get the result. EndExecute has to stop a previously started async operation (possibly interrupting the thread launched by BeginExecute).
Without more details this is the best I can do.




回答4:


If you want to run piece of code asynchronously, you should use BackgroundWorker. Unless of course, the code you are calling doesn't support asynchronous operation natively. Just like Read/Write methods or service calls.

If you want to notify, that the asynchronous operation has finished, use delegate or event callback.



来源:https://stackoverflow.com/questions/6303753/asynchronous-programming-design-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!