I have a method:
public async Task Method(Func<Task> action)
This function basically checks if few seconds have passed since the last run time.
I tried:
Func<Task> timer = async () => { await Task.Delay(3000);};
and invoking it like that
Func<Task> check = await _className.Method(timer);
However it says
Cannot implicitly convert 'void' to 'System.Func<System.Threading.Tasks.Task>'
Basically I am not able to pass a delayed task to a function.
CodePudding user response:
Here's a trivial example of calling Method with a Func<Task>
.
Func<Task> timer = async () => { await Task.Delay(3000);};
await Method(timer);
async Task Method(Func<Task> action)
{
await action();
}
CodePudding user response:
I'm not sure exactly what you're trying to do, but this code works:
public class Program
{
public static async Task Main(string[] args)
{
var sw = Stopwatch.StartNew();
Func<Task> timer = async () => { await Task.Delay(3000); };
var theTask = Method(timer);
await theTask;
Console.WriteLine(sw.ElapsedMilliseconds); // ~3000
}
public static async Task Method(Func<Task> action)
{
await action();
}
}
I just put in var theTask = Method(timer);
to illustrate that you can assign the return value to a Task
before awaiting it.
CodePudding user response:
Okay, so it works like tymtam already said - it looks like my problem was trying to assign end result to Func, i guess i need more sleep.
Thank you for the help tho
EDIT I needed this:
Func<Task> check = async () => await _className.Method(timer);