I currently work to implement a singleton class with a couple of methods. Each method use the same private field that is in fact a connection to a database. In each methods, a reader is trying to be open. As you can see, this is a single connection shared in the entire scope of the application. If you try to open a reader connection in Ado.Net when a reader has already opened, an exception occurs. This case can open if you forget to close a reader after open it but it occurs in my case because I use multiple threads to do some things.
My question is: Must I implement a different mutex object for each method or a single one shared for all methods is enough?
I know that the singleton rarely a good pattern. I also know that a shared connection is not a good practice but remember that my project is a winforms project and is considered legacy. My client also don’t want to paid for a redesign of the application. I just want an answer about how the mutex should be handle in this case.
Thank you very much for your time.
You need a single mutex. If you have more than one mutex controlling a single shared resource (in this case a database connection) then more than one thread can access it at once, which defeats the point of a mutex.