如何编译这个扩展方法?

时间:2022-05-02 22:50:27

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:

我正在尝试为泛型委托Action 创建一个扩展方法,以便能够对Action 方法进行简单的异步调用。它基本上只是实现了你想要执行方法的模式,而不关心它的进展:

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.

问题是它不会编译,因为额外的 会使AsyncActionCallback变得通用并且具有与预期不同的签名。签名void AsyncActionCallback(IAsyncResult)是预期的。

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

有谁知道如何解决这个问题或者想要实现我想要做的事情?

3 个解决方案

#1


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

#2


AsyncActionCallback<T> ?

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

免责声明:不确定上述情况,可能是其中一个“限制”。

#3


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

如果你想保持你的功能分开(而不是lambda)这样的事情:

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

#1


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

#2


AsyncActionCallback<T> ?

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

免责声明:不确定上述情况,可能是其中一个“限制”。

#3


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

如果你想保持你的功能分开(而不是lambda)这样的事情:

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