Samuel
Samuel

Reputation: 12351

Multiple mutex objects for handling each method in multi-threading cases

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.

Upvotes: 0

Views: 436

Answers (2)

Neil Forrester
Neil Forrester

Reputation: 5241

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.

Upvotes: 2

Ivo
Ivo

Reputation: 8372

You'll need to lock all the methods using the same object so each call to the database will be done one by one.

Are you sure it's impossible to create the connection and close it in each method? I think it will be easier than try to fix the behavious with locks :S

Upvotes: 0

Related Questions