Pure.Krome Pure.Krome - 26 days ago 7
C# Question

How to fix this .NET method that has a func as an argument?

I have the following method

public async Task<dynamic> FooAsync(dynamic parameters,
CancellationToken cancellationToken)
{..}


But I can't seem to figure out a way to call it properly using this method:

public async Task<dynamic> TryAsync(Func<dynamic, CancellationToken, Task<dynamic>> func)
{
try
{
await func(); // Doesn't compile. Says it missing the 2 arguments.
}
catch(Exception exception)
{
..
}
}


e.g. code that passes
FooAsync
to
TryAsync
..

public async Task PewPewAsync(..)
{
...
// TODO: Get this to work/compile :(
var result = await TryAsync(FooAsync(parameters, cancellationToken);
...
}


Can anyone help please?

Answer

You have a delegate that takes two parameters (dynamic and CancellationToken) and you're trying to invoke it with zero arguments.

Depending on what you want to do, you can either make TryAsync accept the two parameters and then pass them when calling it:

public async Task<dynamic> TryAsync(
    Func<dynamic, CancellationToken, Task<dynamic>> func,
    dynamic parameters, CancellationToken cancellationToken)
{
    try
    {
        return await func(parameters, cancellationToken);
    }
    catch(Exception exception)
    {
        ..
    }
}

TryAsync(FooAsync, parameters, cancellationToken);

Or you can take a delegate that does not have any parameters and use a lambda when calling it:

public async Task<dynamic> TryAsync(Func<Task<dynamic>> func)
{
    try
    {
        return await func();
    }
    catch(Exception exception)
    {
        ..
    }
}

TryAsync(() => FooAsync(parameters, cancellationToken));