开发者

New connection for each query or one connection for all queries? (CommandBehavior.CloseConnection vs CommandBehavior.Default)

I'm developing a text analysis desktop application, that intensively queries local database (MSSQLCE 3.5). As the user throws text in, it should react in real-time, so I'm using ADO.NET with pure SQL and trying to get the best performance results.

The question is: based on my task, should I keep ONE cached connection (as static variable or singleton) and make queries with CommandBehavior.Default or should I build a new connection for each query and specify CommandBehavior.CloseConnection?

I know that usually it's recommended to close connection ASAP, but should I really do it, if there can be thousands of queries per minute, for example when user pastes a huge text?

Until now, application worked on CloseConnection. Now I tried to turn it to CommandBehavior.Default with single connection. I can see some small performance speed-up and can't see any problems at this time, but I want to know if there are any strings attached, before I put this to deployment.

// one cached connection for all queries
private static DbConnection _connection = null;
public static String MakeQuery()
{            
    if (_connection == null)
    {
        _connection = new SqlCeConnection(...);
        _connection.Open();
    }
    var cmd = new SqlCeCommand("...", _connection);
    using (var reader = cmd.ExecuteReader(CommandBehavior.Default))
    { 

    }
}

vs.

// new connection for each q开发者_JAVA技巧uery
public static String MakeQuery()
{            
    using (var connection = new SqlCeConnection(...))
    {
       connection.Open();            
       var cmd = new SqlCeCommand("...", connection);
       using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
       { 
           ...
       }
    }
}


Personally, when I need many queries in a rapid succession from a non-web application, I prefer to use one shared connection.

The only problem is that you have to keep an eye on it because it may go down unexpectedly due to a network problem or because SQL server thought it better be closed. That is, you must handle StateChanged events.

But connection pooling is on by default anyway. It should be handling all these issues for you. Yes, pooling does add an overhead, but it's not big.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜