I had a multi-threaded TCP server software written in C#. Many of the threads should read from database and i am using SqlDataReader for reading from database. When one thread wants to read from database, there is no problem but when two or more threads want to read from database, this situation starts to be a problem. .NET gives this exception: There is already an open DataReader associated with this Command which must be closed first.
How can i prevent from the error? How can i protect SqlDataReader from multiple access? Is mutex appropriate for this problem?
I suggest creating a new connection per request instead of trying to re-use an existing active connection. I assume you are using some sort of class member or static reference to the connection, instead make it method scoped:
If I had some sample code demonstrating what you currently have, I could adapt that idea for your situation.
As for locking, if you really want to go down this route (seriously, don’t), all you need to do is lock (one of the basic synchronisation primitives):
A mutex won’t necessarily be required as the problem will be process-local, where the lock keyword will suffice. Again, seriously, don’t.