Multi threaded design guidelines for librariesPart I
The major difference between libraries and frameworks is that a framework is something that runs your code, and is in general in control of its own environment and a library is something that you use in your own code, where you control the environment.
Examples for frameworks: ASP.Net, NServiceBus, WPF, etc.
Examples for libraries: NHibernate, RavenDB Client API, JSON.Net, SharpPDF, etc.
Why am I talking about the distinction between frameworks and libraries in a post about multi threaded design?
Simple, there are vastly different rules for multi threaded design with frameworks and libraries. In general, frameworks manage their own threads, and will let your code use one of their threads. On the other hands, libraries will use your own threads.
The simple rule for multi threaded design for libraries? Just don’t do it.
Multi threading is hard, and you are going to cause issues for people if you don’t know exactly what you are doing. Therefor, just write for a single threaded application and make sure to hold no shared state.
For example, JSON.Net pretty much does this. The sole place where it does do multi threading is where it is handling caching, and it must be doing this really well because I never paid it any mind and we got no error reports about it.
But the easiest thing to do is to just not support multi threading for your objects. If the user want to use the code from multiple threads, he is welcome to instantiate multiple instances and use one per thread.
In my next post, I’ll talk about what happens when you actually do need to hold some shared state.