Home > Mobile >  Passing an async Task as Action to method?
Passing an async Task as Action to method?

Time:02-01

I have a method used 100 places that takes in an Action as parameter. I've now introduced a new method that requires awaits and had to be made async. What options do I have for passing that new async Task (previously void) action to the method?

// What I need (want) to do

MethodToBeCalled(DoSomething);

// Methods

void MethodToBeCalled(Action action)
{
    // Do Something
}

async Task DoSomething()
{
    await MethodX();
    return Task.CompletedTask;
}


Tried using Func but didn't find a way to get it to work

CodePudding user response:

You cannot; you would want a Func<Task> instead of Action, for example an overload:

await MethodToBeCalledAsync(DoSomething);

async Task MethodToBeCalledAsync(Func<Task> action)
{
    // ...
    await action();
    // ...
}

Any attempt to do "sync over async" via .Wait(), .GetAwaiter().GetResult(), etc: is dangerous and defeats the entire point of the async Task method.

CodePudding user response:

you can create a new Action delegate that wraps the Task method and use that delegate instead

MethodToBeCalled(() => DoSomething().GetAwaiter().GetResult());

Keep in mind that this approach blocks the calling thread until the Task method completes, so it's not suitable for long-running or I/O-bound operations. For those, you may want to consider refactoring the MethodToBeCalled to accept an asynchronous delegate instead of an Action delegate.

  • Related