I have a server and a client. Server is a web application hosting WCF service. Server uses Linq2SQL DataContext via static singleton which is being initialized upon first access and is never disposed (in my code). Client makes calls to the server via WCF, queries some information from database, makes updates. Everything works fine until several clients access server concurrently. When that happens server throws 开发者_运维问答different exceptions:
Invalid attempt to call Read when reader is closed.
There is already an open DataReader associated with this Command which must be closed first.
As far as I understand the problem is that I'm using static singleton, and it gets somehow shared between client connections, but my primary objective was to minimize amount of connections to database.
Why does this happen?
Linq to SQL DataContext is not thread safe (see MSDN). Typically a DataContext should be instantiated for a distinct unit of work; You could change your code to instantiate one per web request and make sure to close it at the end of the request, and you'll likely be alright.
Don't worry about managing connections, .Net will pool/reuse them for you.
wrap your db Contexts in using statements and you're all set.
Not unless you have some extreme amount of volume and queries should you consider optimizing this.
A singleton means there is only one instance per application/process. An asp.net application uses the same process to serve all requests, but each has their own thread. Therefore you are sharing the same context instance across all requests. simple answer, don't use a singleton pattern for data contexts, this absolutely the wrong thing to do.
精彩评论