Calling a method using delegates asynchronously

using System.Threading;
using System.Runtime.Remoting.Messaging;

private void ActualAsyncMethodCalled()
{
}


private void AsyncMethodCallBack(IAsyncResult result)
        {
            lock (result)
            {
                AsyncResult asyncResult = (AsyncResult) result;

                if (asyncResult.AsyncDelegate != null)
                {
                    Action sourceAction = (Action)asyncResult.AsyncDelegate;
                    sourceAction.EndInvoke(result);
                }
            }
        }

public void Main()
{

        Action asyncAction = ActualAsyncMethodCalled;
        asyncAction.BeginInvoke(new AsyncCallback(AsyncMethodCallBack), null);

}

Using Action<T> if the method to be called takes one parameter, always call end invoke when you call begin invoke. Only in windows forms Control.BeginInvoke, this rule is explicitly not required as per MSDN.

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory