c# asynchronous invoke of generic delegates

Yonatan Nir

I want to invoke a general Delegate using async await. I am not working with a prebuilt delegates, but rather the general Delegate class which can receive arguments as an array of objects.

I am doing something like this:

public object InvokeAction(Delegate action, object[] actionArgs = null)
    {
        if(action == null)
        {
            return null;
        }
        return action.DynamicInvoke(args);
    }

What I want to do is give an option to run the delegate using await but since DynamicInvoke returns an object, it doesn't have an awaiter.

Is there a way to define a general delegate and make an asynchronous invocation? If not a generic one, is there some version which is close to a generic delegate (It's ok to force the user to some delegate definition) which can be invoked the way I want?

Johnathan Barclay

Your delegate needs to return an awaitable type, generally this is Task or Task<TResult>.

You could check for this at runtime:

public async Task<TResult> InvokeAction<TResult>(Delegate action, object[] actionArgs = null)
{
    //...
    var result = action.DynamicInvoke(actionArgs);
    if (result is Task<TResult> task) return await task;
    return (TResult)result;
}

However, as long as actionArgs are not modified within your method, you could statically type your delegate, and use a closure:

public async Task<TResult> InvokeAction<TResult>(Func<Task<TResult>> action)
{
    //...
    return await action();
}

var result = InvokeAction(() => YourMethodAsync(arg1, arg2));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related