I'm working on a project that creates like 20~50 new tasks every 30~80 seconds. Each task lives for 10~20 seconds.
So I'm using a Timer to create those new tasks, but everytime I always recreate the same task, the code is like this:
public class TaskRunner : IDisposable
{
private readonly Timer timer;
public IService service;
public ThreadRunner(IService service) {
this.service = service;
timer = new Timer(10000);
timer.Elapsed += Execute;
timer.Enabled = true;
}
}
private void Execute(object sender, ElapsedEventArgs e)
{
try
{
Task.Factory.StartNew(service.Execute);
}
catch (Exception ex)
{
logger.ErrorFormat("Erro running thread {0}. {1}", service, ex);
}
}
public void Dispose()
{
timer.Dispose();
}
}
My question is, theres any way to create a task and keeping restarting it, so I dont need to start a new task Task.Factory.StartNew(service.Execute); everytime?
Or thats something that I don't have to worry about, and it's ok to keep creating new tasks?
Theres any guide/best practices on how should I works on this scenario, with that kind of threads ?