问题
I made a custom ThreadPool optimized for my specific needs. However, when there are multiple AppDomains in the process, the CLR ThreadPool is able to be shared across all the AppDomains and I would like to be able to reproduce this behavior.
This could be done using MarshalByRefObject and Remoting in order to create a distributed ThreadPool, but I fear that it will add unwanted overhead since the key goal of the custom thread pool is performance.
Another theoretical solution would be to hack the AppDomain memory boundary using an unmanaged object. If I'm correct, the memory boundary in AppDomain only apply to managed objects, so there could be one managed wrapper in each AppDomain all pointing to the same unmanaged object.
So my questions are:
- Is there a way to make a custom thread pool using remoting with minimal overhead?
- If not, is it possible to share an unmanaged object across AppDomain?
回答1:
Create a new threadpool instance in each appdomain, but then use a semaphore to control the total number of threads running across all instances. This means you can still get the same total concurrent jobs processed, but don't have the grief of marshalling.
The MSDN docs have an example.
回答2:
After thinking more about it, it's probably a bad idea to try to reimplement a process wide ThreadPool, the CLR ThreadPool is already optimized for this.
For my case, I wanted more flexibility to be able to prioritize work items queued into the pool, this can be done with a layer built on top of the existing CLR ThreadPool.
来源:https://stackoverflow.com/questions/1751294/net-how-to-create-a-custom-threadpool-shared-across-all-the-appdomain-of-a-proc