[英]Pass Func<Task> as parameter
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.这个 function 基本上检查自上次运行时间以来是否经过了几秒钟。
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>'
无法将“void”隐式转换为“System.Func<System.Threading.Tasks.Task>”
Basically I am not able to pass a delayed task to a function.基本上我无法将延迟任务传递给 function。
Here's a trivial example of calling Method with a Func<Task>
.这是一个使用
Func<Task>
调用 Method 的简单示例。
Func<Task> timer = async () => { await Task.Delay(3000);};
await Method(timer);
async Task Method(Func<Task> action)
{
await action();
}
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);
我只是把
var theTask = Method(timer);
to illustrate that you can assign the return value to a Task
before awaiting it.说明您可以在等待
Task
之前将返回值分配给它。
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.好的,所以它就像 tymtam 已经说过的那样工作 - 看起来我的问题是试图将最终结果分配给 Func,我想我需要更多的睡眠。
Thank you for the help tho谢谢你的帮助
EDIT I needed this:编辑我需要这个:
Func<Task> check = async () => await _className.Method(timer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.