Friday, October 10, 2008

Custom ThreadPool implementation

.NET Framework BCL contains very nice implementation of thread pool (System.Threading.ThreadPool class).
But this class is not suitable for following scenarios:
1. Long-running operations. Usually for long-running operations it is recommended to use Thread class.
2. ThreadPool is per process. It means, that situation when there is no available threads in ThreadPool can happen pretty often. What if you have very important and emergent work items and do not want rely on such a risk? But pretty often, especially when you have application with number of app domains (like IIS or SQL server) you can run out of threads in thread pool...
3. ThreadPool does not support IAsyncResult. BeginInvoke methods of all delegates internally pass control to ThreadPool, but ThreadPool itself does not support IAsyncResult.

It is just initial version of CustomThreadPool and I plan to extend it in future.

Generally, there are number of strict recommendations when you should use ThreadPool and when you should use Thread class directly or MulticastDelegate.BeginInvoke. Ideally I plan to create ThreadPool that would suit for those scenarios applicable for Thread class and BeginInvoke. The main problem of System.Threading.ThreadPool is that it is per process. So if you have set of very important tasks to do and also have set of third-party assemblies that you host in the application, there is always probability that your important tasks will be delayed. In case of CustomThreadPool you have separate threadpool for each application domain.
Ok, I know, there is number of maximum threads allowed per process and if there is too much threads, thread switch context can be awfull...

The sources of ThreadPool implementation can be found on CodeProject.

The code above is intended to demonstrate an idea how it could be implemented. I haven't tested it carefully, but it seems to be working ;)

No comments: