❔ ✅ Why should I use Func<Task> in this situation?
I have following class:
logic is simple
I just don't understand following:
if I change Func<Task> to simple Task everythink wouldn't work
public static class MemoryLeaksTest
{
private static readonly ILiteCollectionAsync<MqttDelivery> _liteCollection;
public static void Run()
{
new TimerService(TimeSpan.FromSeconds(1))
.Start(Write);
new TimerService(TimeSpan.FromSeconds(5))
.Start(Read);
}
private static async Task Read() =>
await _liteCollection
.Query()
.Limit(40)
.ToList();
private static async Task Write() =>
await _liteCollection
.Upsert(new MqttDelivery());
}public static class MemoryLeaksTest
{
private static readonly ILiteCollectionAsync<MqttDelivery> _liteCollection;
public static void Run()
{
new TimerService(TimeSpan.FromSeconds(1))
.Start(Write);
new TimerService(TimeSpan.FromSeconds(5))
.Start(Read);
}
private static async Task Read() =>
await _liteCollection
.Query()
.Limit(40)
.ToList();
private static async Task Write() =>
await _liteCollection
.Upsert(new MqttDelivery());
}public class TimerService
{
private Task _timerTask;
private readonly PeriodicTimer _timer;
private readonly CancellationTokenSource _cts = new();
public TimerService(TimeSpan interval)
{
_timer = new PeriodicTimer(interval);
}
public void Start(Func<Task> f)
{
_timerTask = Interval(f);
}
public async Task Stop()
{
_cts.Cancel();
if (_timerTask != null)
await _timerTask;
_cts.Dispose();
}
private async Task Interval(Func<Task> f)
{
try
{
while (await _timer.WaitForNextTickAsync(_cts.Token))
await f();
}
catch (OperationCanceledException) { }
}
}public class TimerService
{
private Task _timerTask;
private readonly PeriodicTimer _timer;
private readonly CancellationTokenSource _cts = new();
public TimerService(TimeSpan interval)
{
_timer = new PeriodicTimer(interval);
}
public void Start(Func<Task> f)
{
_timerTask = Interval(f);
}
public async Task Stop()
{
_cts.Cancel();
if (_timerTask != null)
await _timerTask;
_cts.Dispose();
}
private async Task Interval(Func<Task> f)
{
try
{
while (await _timer.WaitForNextTickAsync(_cts.Token))
await f();
}
catch (OperationCanceledException) { }
}
}logic is simple
I just don't understand following:
if I change Func<Task> to simple Task everythink wouldn't work