Asynchronous programming design pattern

2019-03-21 15:14发布

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 !

4条回答
放我归山
2楼-- · 2019-03-21 15:55

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();
    }
}
查看更多
神经病院院长
3楼-- · 2019-03-21 15:59

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楼-- · 2019-03-21 16:00

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.

查看更多
唯我独甜
5楼-- · 2019-03-21 16:08

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.

查看更多
登录 后发表回答