传入 Task 以使方法更通用以进行重用不会异步运行
本文关键字:异步 运行 方法 传入 Task | 更新日期: 2023-09-27 18:31:18
所以本质上我想将操作或函数 Lambda 语句传递给一个方法,以使用不同的方法重用通用计时器功能。 所以我可以做一些像GenericTimer(1000,Task1DoesThisThing)和GenericTimer(3000,Task2DoesThisCompleteOtherThing)这样的事情。 我只想要可重用性,不在乎是否给了我与我正在做的事情截然不同的方法。
private static void TimerGeneric(int duration, Task timerDuration)
{
var timer = new Timer(duration);
timer.Elapsed += async (sender, e) => await timerDuration;
timer.Enabled = true;
}
private static void TimerSetupWithRefresh(int refreshDuration)
{
Timer timer = new Timer(refreshDuration);
timer.Elapsed += async (sender, e) => await Refresh();
timer.Enabled = true;
}
private static async Task Refresh()
{
Console.WriteLine("Specific is: " + DateTime.Now);
}
public class Poc { public int Id { get; set; } public string Value { get; set; }}
static void Main(string[] args)
{
//Works just as expected and refreshes every second for the 'Refresh()' method.
TimerSetupWithRefresh(1000);
//Below does not work yet I would expect a Task passed in via signature with near same method would behave the same.
TimerGeneric(1000, new Task(() => { Console.WriteLine("Passed in Task is: " + DateTime.Now); }));
Console.ReadLine();
}
当前您正在传递从未启动的Task
。我认为您真正想要的是获取一个调用异步方法的委托,这可以使用 Func<Task>
类型的参数来完成,如下所示:
private static void TimerGeneric(int duration, Func<Task> timerDuration)
{
var timer = new Timer(duration);
timer.Elapsed += async (sender, e) => await timerDuration();
timer.Enabled = true;
}
然后像这样使用它:
TimerGeneric(1000, async () => { Console.WriteLine("Passed in Task is: " + DateTime.Now); });
尽管异步方法最好实际执行一些异步工作,否则只需返回已完成的Task
:
TimerGeneric(1000, () =>
{
Console.WriteLine("Passed in Task is: " + DateTime.Now);
return Task.CompletedTask;
});
这可能是优先的,因为它消除了同步实现不需要的底层异步状态机。