Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action T synchronous and asynchronous

I have a ContextMenuStrip control that allows you to execute an action is two different flavors: Sync and Async.

I am trying to cover everything using Generics so I did this:

public class BaseContextMenu<T> : IContextMenu
{
   private T executor;

   public void Exec(Action<T> action)
   {
      action.Invoke(this.executor);
   }

   public void ExecAsync(Action<T> asyncAction)
   {
       // ...
   }

How I can write the async method in order to execute the generic action and 'do something' with the menu in the meanwhile? I saw that the signature of BeginInvoke is something like:

asyncAction.BeginInvoke(this.executor, IAsyncCallback, object);
like image 412
Raffaeu Avatar asked Mar 12 '10 16:03

Raffaeu


2 Answers

Here is Jeffrey Richter's article on .NET asynchronous programming model. http://msdn.microsoft.com/en-us/magazine/cc163467.aspx

Here is an example of how BeginInvoke can be used:

public class BaseContextMenu<T> : IContextMenu
{
    private T executor;

    public void Exec(Action<T> action)
    {
        action.Invoke(this.executor);
    }

    public void ExecAsync(Action<T> asyncAction, AsyncCallback callback)
    {
        asyncAction.BeginInvoke(this.executor, callback, asyncAction);
    }
}

And here is a callback method that can be passed to the ExecAsync:

private void Callback(IAsyncResult asyncResult)
{
    Action<T> asyncAction = (Action<T>) asyncResult.AsyncState;
    asyncAction.EndInvoke(asyncResult);
}
like image 142
Andrew Bezzub Avatar answered Sep 25 '22 07:09

Andrew Bezzub


Simplest option:

// need this for the AsyncResult class below
using System.Runtime.Remoting.Messaging;

public class BaseContextMenu<T> : IContextMenu
{
    private T executor;

    public void Exec(Action<T> action) {
        action.Invoke(this.executor);
    }

    public void ExecAsync(Action<T> asyncAction) {
        // specify what method to call when asyncAction completes
        asyncAction.BeginInvoke(this.executor, ExecAsyncCallback, null);
    }

    // this method gets called at the end of the asynchronous action
    private void ExecAsyncCallback(IAsyncResult result) {
        var asyncResult = result as AsyncResult;
        if (asyncResult != null) {
            var d = asyncResult.AsyncDelegate as Action<T>;
            if (d != null)
                // all calls to BeginInvoke must be matched with calls to
                // EndInvoke according to the MSDN documentation
                d.EndInvoke(result);
        }
    }
}
like image 34
Dan Tao Avatar answered Sep 25 '22 07:09

Dan Tao