Triynko
Triynko

Reputation: 19204

Is it ok to use long-lived Tasks that aren't long-running Tasks?

For example, if I had to choose between these two, should I dedicate a Thread to a periodic cleanup task, or should I just use a looping Task that never finishes?

Because the Thread would be sleeping most of the time, only occasionally waking up to a signal (not necessarily at any particular time) to do a tiny bit of cleanup, I feel that the thread would be wasted. One thread may be no big deal, but I'll potentially have dozens of these.

Instead of creating a dedicated Thread that's usually asleep and consuming resources, I would like to use a Task that loops forever, waiting (asynchronously) on a 'wake' signal during each iteration.

This wouldn't be a "long-running" Task (i.e. it would not be CPU-bound for very long), but it would be a "long-lived" Task (i.e. it never completes and will typically just be tracked in some await queue).

Suppose I start many of these "long-lived" Tasks. Will I run into any performance problems with this approach as a result of these long-lived Tasks simply existing? It seems simpler to manage the work with Tasks and let them run on ThreadPool threads. The work doesn't need any special priority over other work that might also run on ThreadPool threads.

Upvotes: 1

Views: 125

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40938

I wouldn't use either.

sleeping most of the time, only occasionally waking up to a signal to do a tiny bit of cleanup

This seems like the perfect use case for a Timer. While the time is ticking, nothing exists (neither a thread nor a task). When the time elapses, the event handler is run a ThreadPool thread.

Upvotes: 3

Related Questions