views:

100

answers:

4

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 ?

+4  A: 

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.

Hans Passant
+1  A: 

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?

Anthony Williams
A: 

Use the ThreadPool instead. Rather than managing tasks, you'd be better off letting the ThreadPool to spawn each thread, threadpool management offers very low overhead and simplistic coding.
Here is how to use ThreadPool with examples:
http://msdn.microsoft.com/en-us/library/3dasc8as(VS.80).aspx

http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx

Michel Triana
`Task.Facotory.StartNew` (and task in general) already uses `ThreadPool` underneath but adds a layer with task-scheduling, task stealing etc. :)
lasseespeholt
Task do use the (improved) Threadpool. With options.
Henk Holterman
+1  A: 

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 anyway 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.

Henk Holterman