user65199
user65199

Reputation:

How to make this extension method compile?

I am trying to create an extension method for the generic delegate Action<T> to be able to make simple asynchronous calls on Action<T> methods. It basically just implements the pattern for when you want to execute the method and don't care about it's progress:

public static class ActionExtensions
{
    public static void AsyncInvoke<T>(this Action<T> action, T param) {
        action.BeginInvoke(param, AsyncActionCallback, action);
    }

    private static void AsyncActionCallback<T>(IAsyncResult asyncResult) {
        Action<T> action = (Action<T>)asyncResult.AsyncState;
        action.EndInvoke(asyncResult);
    }
}

The problem is that it won't compile because of the extra <T> that makes the AsyncActionCallback generic and have a different signature than expected. The signature void AsyncActionCallback(IAsyncResult) is expected.

Does anyone know how to work around this or to accomlish what I am trying to do?

Upvotes: 4

Views: 324

Answers (3)

Rene
Rene

Reputation: 2155

If you want to keep your function separated (not as lambda) what about something like this:

public static void AsyncInvoke<T>(Action<T> action, T param)
{
    action.BeginInvoke(param, new AsyncCallback(AsyncActionCallback<T>), action);
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

public static void AsyncInvoke<T>(this Action<T> action, T param)
{
    action.BeginInvoke(param, asyncResult => 
    {
        Action<T> a = (Action<T>)asyncResult.AsyncState;
        a.EndInvoke(asyncResult);
    }, action);
}

Upvotes: 7

leppie
leppie

Reputation: 117220

AsyncActionCallback<T> ?

Disclaimer: not sure about the above, could be one of those 'limitations'.

Upvotes: 0

Related Questions