Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I encapsulate Task in a Class?

I'm building an application having multiple long running worker threads which need to be running 24x7. Each worker is a method in a class called Bot. Start/Stop of the Bot is controlled by the class itself. So if I need 10 bots running, I just need to instantiate 10 Bot, store in a List<Bot>, and start everyone of them. I also have a BotManager class to manage all the currently running Bot

Now, I wanted to use Task instead of Thread for each of the workers, as they're only spending less than 5% of the time doing any processing.

Should I keep a Task in each class or should I inherit my Bot from Task?

like image 760
faulty Avatar asked Nov 19 '25 04:11

faulty


1 Answers

I wouldn't descend from Task. You're not really extending the idea of "task" and making something that, to code that uses it, is a task with extra features; instead you're just making something that happens to use tasks for its implementation.

I'm also not sure Task is a good fit here. If the idea is that these keep running in the background, then that's not playing to TPL's strengths. The best time to use Task is when you need composability -- a well-defined task that runs, completes, and then notifies other tasks that it's done and they can start working on its results.

like image 152
Joe White Avatar answered Nov 21 '25 19:11

Joe White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!