0

I would like to know if there 'right' method to loop one task forever?

What I've tried:

private static void A()
{
    Task.Run(B);
}

private static async Task B()
{
    while (true)
    {
        Task Delay = Task.Delay(10000);
        await C();
        await Delay;
    }
}

private static async Task C()
{
    // some async code that will work every 10s
}

It is working, but I want to understand is there any better options to do the same.

Thanks in advance.

Develuxe
  • 1
  • 1
  • For maintaining a consistent interval it's better to create the `Delay` task before calling the `C`, and `await` it after, as shown [here](https://stackoverflow.com/questions/30462079/run-async-method-regularly-with-specified-interval/62724908#62724908). – Theodor Zoulias Jan 23 '22 at 10:09
  • @TheodorZoulias Thanks, edited post, but is it right way to let it work like that? – Develuxe Jan 23 '22 at 10:14
  • Also if you think that it's a good idea to fire-and-forget a task ([it rarely is](https://stackoverflow.com/questions/61316504/proper-way-to-start-and-async-fire-and-forget-call/61320933#61320933)), it's better to be explicit and assign the task to a discard: `_ = Task.Run(B);` – Theodor Zoulias Jan 23 '22 at 10:14
  • 1
    @TheodorZoulias Thank you, will read once again about fire-and-forget too! – Develuxe Jan 23 '22 at 10:19
  • 2
    Why not use a timer that fires every 10 seconds? – Hans Kesting Jan 23 '22 at 11:10
  • 1
    @HansKesting the main problem with the timers that schedule work on the `ThreadPool`, is that they are reentrant. In most cases you don't want your periodic work to overlap, and trying to enforce a non overlapping policy on timer events is a pain. – Theodor Zoulias Jan 23 '22 at 12:54
  • 1
    What kind of application is this? (ASP.NET, desktop, etc.) Either way, I think a better solution is a Timer. That's what they're for. – Gabriel Luci Jan 23 '22 at 16:05

0 Answers0