views:

131

answers:

3

Hi everybody I have a contextmenustrip control that allows you to execute an action is two different flawours. Sync and Async. I am trying to covert 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(thi.executor, IAsyncCallback, object);
A: 

you pointed to right method. read this article to better understand the whole concept.

Andrey
A: 

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);
}
Andrew Bezzub
let me have a look
Thanks, this is what I was looking for. I had just an issue with the lambda expression, I didn't need a course on multithreading programming. ;-)
A: 

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);
        }
    }
}
Dan Tao