Restart a task or create a new one?
I'm working on a project that creates like 20开发者_Go百科~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 ?
Your Execute method already runs on a thread. A threadpool thread that was started by the System.Timers.Timer you are using in order to raise the Elapsed event. Don't start another thread, just use the one that was handed to you. Threadpool threads are very cheap and recycle automatically.
To the revised question:
should I create a new Task every time, or can I just restart it?
The answer should be very clearly: Yes, use a new one each time. Don't try in any way to re-use a task, the shorter the use the better.
While Threads are very expensive to create, Tasks are already using the ThreadPoool to address that problem. Don't interfere with it, you'll only introduce problems.
Rather than restarting each of the threads when the timer triggers, why not have each thread run a loop that runs the specified code at the required frequency?
精彩评论