In the process of refactoring some legacy code at work and part of it is to convert an instance of List<Action>
to List<Func<Task>>
. Elsewhere in the codebase, there are several instances of something along the lines of this:
entity.Tasks.Add(() =>
{
_service.Process(operation)
}
The above would work fine when the Tasks property was List<Action>
, but gives errors when turned into List<Func<Task>>
with no obvious way to fix it.
I know next to nothing about Func, Task, Action, asynchronous/synchronous programming, particularly in C#. Any help provided is immensely appreciated or even just a referral to information where I could find the information needed to solve this myself.
What you have to do is to create a function that returns a Task. A solution could be creating a task that internally executes your synchronous code and then add it to the list. Like this:
entity.Tasks.Add(() => Task.Run(_service.Process(operation)));
Just note that the code only creates a function that returns a Task but the Task won't be executed until you ask for it.
Here is more info about the topic: