views:

144

answers:

2

Hi, I would like to ask you for help, since my approach was not good. On the server side, there are clients connected (each client is represented by my Client class). Each client needs to comunicate with DB behind the server, also there is a need of multiple connections at the same time.

I am considering to have SQLConnection and SQLReader instance in each client instance, that would surely work but I am not sure whether there is not any better way. Of course performance is everything what matters. Thanks!

EDIT: The usual traffic is about 5 requests/sec (Opening connection is so often is laggy).Maximum number of users is not higher than 100.

A: 

I typically let the data-fetching methods create connections as needed. I am yet to come across a situation where this is not fast enough. Don't forget that (at least with SqlConnection) there is some internal connection pooling to increase performance. This approach will effectively take away the need to maintain data objects per client and so on.

Simple example:

private static IEnumerable<SomeType> GetSomeData(string someInput)
{
    IEnumerable<SomeType> result = null;
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        // put whatever code is needed to populate the result here
    }
    return result;
}

You could also look into using Linq-to-SQL, which may result in very simple and performant data access code.

Fredrik Mörk
Thanks...but what if more threads run this method, if it is static? How about thread safety in the example above?
Tomas
@Tomas: since the example above does not use any shared resources (apart from the database, the code of which is out of our control anyway) there are no real threading issues here; each call to the method will operate on its own `SqlConnection` object, its own `result` variable and so on.
Fredrik Mörk
A: 

I am thinking of something like a connection pool. We just create a limited number of Connection objects and share them among the clients. Since every client is not using the connection all the times I think this is possible.

Chathuranga Chandrasekara