0

I have a scenario like where I am using Task Parallel Library and I need to restrict the number of objects (here tasks) created. That means it will reuse the existing task and I am thinking of using Object pool design pattern to implement this functionality. But when I do some research understood that “restart a running or completed Task is not supported”. So my question is can I use object pool pattern here even though it is not reusing the task. Because anyway I am restricting the number of task to be created. Please give some advice.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
Dev
  • 309
  • 1
  • 8
  • 24
  • 1
    Search SO for `SemaphoreSlim` and `WaitAsync`, e.g., [this](http://stackoverflow.com/questions/22492383/throttling-asynchronous-tasks/22493662#22493662) or [this](http://stackoverflow.com/a/23483308/1768303). Also search for `TPL Dataflow` and `MaxDegreeOfParallelism`. – noseratio Jun 19 '14 at 06:21

1 Answers1

1

Task in an object that represents an executable unit of work (synchronous or asynchronous). It seems you're trying to restrict the execution, while Object Pool is used to restrict the amount of objects created. There's no real point to reuse a Task (unlike a db connection for example).

To restrict concurrent execution you can use SemaphoreSlim with Wait/WaitAsync or use TPL Dataflow with MaxDegreeOfParallelism.

To restrict the number of threads used you need to create a custom TaskScheduler

i3arnon
  • 113,022
  • 33
  • 324
  • 344
  • @ Noseratio and @ I3arnon--> Thanks for the reply: My question is whether i can use Object pool design patter here to implement the restricting object usage. I have heard like that design pattern is used in such kind of scenario – Dev Jun 19 '14 at 10:48
  • 1
    @Dev not really, because you can't reuse a task. you can have an object pool of some other object. The real question is why would you want to. what are you trying to improve? – i3arnon Jun 19 '14 at 10:51
  • I was trying to apply some design pattern into the project if it really matches the scenario. – Dev Jun 20 '14 at 06:25