-2

I want to launch a method in a separated thread periodically (every minute). I was using System.Timers.Timer but I realize that Timers cause memory leaks.

I need to remove Timers and use task. The first idea is launch a Task in the following way:

_taskWork = Task.Factory.StartNew( DoWork );

And in the DoWork method:

private void DoWork()
{
    While(true)
    {
        // Stuff here

        Thread.Sleep(60000);
    }
}

Is there any way to launch a task avoiding this approach?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Maybe to look into some library like `quartz.net`? – Johnny Mar 08 '19 at 07:47
  • You shouldn't use `Thread.Sleep` with tasks, instead use `await Task.Delay(60000);`, and make your method async. Also, you probably shouldn't be using `Task.Factory.StartNew`, instead, after making your method `private async Task DoWork()`, simply call it. – Lasse V. Karlsen Mar 08 '19 at 07:51
  • 7
    What do you mean by "Timers cause memory leaks"? – V0ldek Mar 08 '19 at 07:52
  • 6
    Also, how do you figure that timers cause memory leaks? – Lasse V. Karlsen Mar 08 '19 at 07:52
  • 7
    Timers are *designed* for this use case. *Misuse* of timers may have led you to having a memory leak but that would have been about *your code*, not timers themselves. Unfortunately, you've not shown us the code that "causes memory leaks". – Damien_The_Unbeliever Mar 08 '19 at 07:54
  • checkout `hangfire` to execute code periodically(cron jobs). (https://www.hangfire.io/) – Aarif Mar 08 '19 at 08:02

1 Answers1

0

Similar Method : The async equivalent is a while loop with Task.Delay (which internally uses a System.Threading.Timer):

public async Task PeriodicFooAsync(TimeSpan interval, CancellationToken cancellationToken)
{
    while (true)
    {
        await FooAsync();
        await Task.Delay(interval, cancellationToken)
    }
}

This Work fine for me please refer this for more understanding.

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57