fahadash
fahadash

Reputation: 3281

Writing my own IScheduler to to manage threads, what should be the best way to do this?

I am using ReactiveUI's ReactiveCommand feature which is very cool and serves the purpose. The only issue I am having with that is, ReactiveCommand when instantiated needs an IScheduler implementation and currently it only provides two MainThreadScheduler and TaskPoolScheduler and they both allow creating of separate thread per ReactiveCommand instance which I cannot afford because my application has enormous amount of ReactiveCommand instances.

So I decided to have my own IScheduler implementation that I could pass to ReactiveCommand constructor and what I would like to do is have some sort of configurable MaxThread; which will not allow more than the MaxThread threads.

There are two ways I can think of as or right now

  1. Whenever application starts, start those threads and put them in Wait state trying to remove Tasks from ActionBlock, When Schedule is called, add that Action object to ActionBlock instance.

  2. Create and Destroy, basically same as 1 but once a task is complete, end the thread instead of keeping it alive.

Does anybody have any suggestion as to how we should accomplish this ? Any input, code-sample, link to articles or something on Github/Codeplex would be appreciated.

Upvotes: 2

Views: 1383

Answers (3)

jamespconnor
jamespconnor

Reputation: 1412

If you don't want to start new threads on long running tasks on the default scheduler then you can just use the default scheduler with the ISchedulerLongRunning optimisation disabled like so:

Scheduler.Default.DisableOptimizations(typeof(ISchedulerLongRunning));

Things like ObserveOn will create a new thread for each subscription if you don't do this

Upvotes: 2

Lee Campbell
Lee Campbell

Reputation: 10783

So why do you not want to use the DefaultScheduler, which will kick out to a ThreadPool for you?

Also, if internally something is calling ScheduleLongRunning(), are you sure that this is what you want anyway? It seems like you could be introducing convoys and thread contention which is a complex domain to work in.

Maybe what you are actually looking to do is to either

  1. Prime your thread pool so you dont get pauses when it needs to add threads to it
  2. Create a better concurrency design for you application. If you have 80 things all scheduling form the UI at once, it sounds like something is not quite right.

I imagine Paul will have some insight?

Upvotes: 1

Yaser Moradi
Yaser Moradi

Reputation: 3317

Implement IScheduler with ThreadPool of .NET, and set maximum threads of ThreadPool easily.

There are several implementations of ThreadPool on code project, You can use them if you are not

interested in default application pool of .NET or you might not like to use ThreadPool of .NET in

this situation

Let me know, If you have problem in implementing IScheduler itself.

Good luck

Upvotes: 0

Related Questions