I like the Inversion of Control (IOC) pattern 开发者_如何转开发and use it a lot. As usual I have my problems with threads and where they sit in the OO ecosphere of .NET.
I was thinking about threading and using the "built-in" Threadpool Class in .Net, and realised that it operates on a whole different level to your code and that it was outside of the scope of the IOC pattern with regards to IOC containers such as Unity.
I don't know a heck of a lot of where a Thread would exist in the realms of IOC, but if can be treated as a class then it could be a candidate for inclusion into your IOC framework. If this be the case, how do you deal with use of the ThreadPool.
Would this assessment be correct.
Firstly I actually never use the ThreadPool
directly, but have an interface IThreadPoolService
which I resolve via an IoC container. This is very helpful for unit testing logic where the threading aspect would make things more difficult but add nothing to the testing aspect. I can mock out the service with a non-threaded test version.
I don't feel that using the ThreadPool
violates IoC as the ThreadPool
is not actually controlling tasks per se, it's only responsible for calling the entry point. It's also not "creational" which is a core aspect of an IoC container.
Using an IoC container to resolve an IThreadPoolService
gives you the usual benefits of adding a layer of indirection e.g. you can change implementations and add additional behaviours such as logging which of course can be supported via IoC\DI.
Threading and IoC don't have much in common. The loose coupling can take place regardless of threading being involved. Attempting to provide an interface for the Thread class is possible however you don't abstract away the other .NET framework classes do you?
Take a service which will expose data in some form. If the service decides to provide async behavior via threading the consumer will have to take this into account. Making a call to the service would still be within the realm of IoC.
With the service being exposed as an interface it can get changed out as needed while still providing the desired behavior which in this case would be async behavior. This would allow you to define a method in the interface and a callback/event once the data is ready all while still making use of Unity and other IoC frameworks.
精彩评论