Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# asynchronous invoke of generic delegates

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?

like image 256
Yonatan Nir Avatar asked May 26 '26 01:05

Yonatan Nir


1 Answers

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));
like image 58
Johnathan Barclay Avatar answered May 27 '26 13:05

Johnathan Barclay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!