I have written a Windows Service which listens for data from a third party service, holds it in memory for a short time and periodically all the new data is flushed to the database.
I was initially opening a new connection each time I needed to flush the data and closing it again afterwards. (Every 5 seconds or so)
As the server seems to be getting hammered I have changed that so there is a single connection opened and reused for the life of the application.
Just wondering if this is a bad idea?
I usually do web stuff where the connection is open and closed over the life of a single request. What is the best practice for a windows service that needs to do the sort of operation I have described?
I was going to make a fault tolerant connection like this:
private SqlConnection _sqlConnection;
public SqlConnection SqlConnection
{
get
{
if (_sqlConnection == null || !_sqlConnection.State.Equals(ConnectionState.Open))
{
var conn = new SqlConnection(_connectionString);
conn.Open();
return conn;
}
return _sqlConnection;
}
}
so if some reason the existing connection is closed or faulted in some way we would get a new open one
is that bad design for any reason?
If you are the single user of the database, hold onto the connection. If not you can really rely on connection pooling to do that for you.
I personally would go for opening the connection everytime. In .NET 2.0 a new feature was implemented so that if you have an open connection to a sql server and sql server gets restarted, etc... your connection becomes invalid and that is not something I can risk my service with. See my post from some years ago.
Call me conservative but I still think that leaving it up to the connection pool to manage the physical connections to the database is a better choice. So just open and close the connection normally, and leave to the pool to decide what to do. I've done that in web services without any problems, and you will have more connections available to handle the load.
I would not try to maintain an open connection. There will be lots of edge cases where the connection will be become unusable and your code for managing the connection and making sure the old duff connection is correctly disposed would have to be absolutely bullet-proof.
I recommend the more common connection use pattern of open, use, close/dispose. The code will be much easier to write and maintain. Be absolutely sure you are disposing of all command and connection objects once you're done with them. Monitor your app with a profiling tool, and keep a check on the number of open database connections at the server to make sure your code is working the way you intended.
How often you need to dump the data into the database (and therefore open/use/close database connections) depends on a number of factors such as how much data will be in-memory before being dumped, the capability of the database server to consume the data, and the risk of losing data if you've accepted it from the web service, but haven't written it to the database and your service or the server crashes.
If your data is precious, you might want to consider having two processes. One process calls the web service and stores the received data securely in a message queue. Another process reads the messages from the queue and puts the data in the message in the database.
This way of handling this process means you can receive data whilst the database is temporarily down, and all the data will eventually be stored in the database.
Whilst this is a solid solution, it could just as easily be considered overkill, depending on your requirements.
Related
We have a 3-tier application with a C# client, a C# WCF web service layer, and a SQL Server database. The web service connects to the database with ADO.NET. All of our C# code is using the .NET Framework 2.0.
Recently, a customer performed a stress test on our application. During the test, the web server generated a lot of errors like the following:
Could not connect to database for connection string '...'. Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
I am aware there are ways to catch connection errors when the connection pool is full and try acquiring a connection outside of the connection pool. We also found several queries that needed to be tuned, but they dot not explain web server connection timeouts.
We're trying to figure out why the web server was timing out connecting to the database. I have setup the web server to enable all of the ADO.NET performance counters. However, I don't see anything related to the times required to connect or connection timeouts or the like. Ideally, we would be able to graph the connection times in perfmon next to the other ADO.NET counters.
Is there a way to monitor the ADO.NET performance in acquiring connections?
I imagine we could create our own "average connection open time" performance counter by timing attempts to open connections, but I'd rather use something that already exists.
You can use perfmon to get this information. You'll need to attach to the User Connections monitor under SQL Server: General Statistics. Here is the blog post I grabbed that from. This will let you know at what point in time connections are being left open.
You will then need to correlate that with application tasks (i.e. stuff you're doing in the application when you see them continually climb).
Once you've done that you're going to want to get those connections inside a using statement if you don't already:
using (SqlConnection cn = new SqlConnection("some connection string"))
{
cn.Open();
...
}
by doing this you won't need to issue a Close and you won't have to worry about them getting disposed of properly.
In short, the performance counter should help you track down the code in the application that's causing the issue, but it won't be down to the line per say, it will take a bit more effort even from there.
I am receiving data through a com port continuously and doing some decoding. When decoding is done i have to store the results in a sql database. I am thinking since the decoding is done (in a while loop always running) dozens of times per second and data need to be stored to the database dozen of times every second if it is wise to open and close the connection to the sql server in each while loop or just leave it open and continue to write data to the database.
First of all is this possible? Secondly if the connection remains open can third party applications or computer access the database at the same time and read data as my programm stores data?
A database supports more than one concurrent connection, so yes it is very feasible in this scenario to leave the DB connection open - you will only lock out others if you have i.e. a long running query that results in row/ table locking. Just close the connection when you are done.
Also consider though that most DBs (i.e. SQL Server) use connection pooling internally, so even though you close a DB connection it just goes back to the pool and is not physically closed - the pool manages the physical DB connections - this results in much better performance, so the impact of opening/closing connections rapidly is reduced.
From MSDN:
Connection pooling reduces the number of times that new connections
must be opened. The pooler maintains ownership of the physical
connection. It manages connections by keeping alive a set of active
connections for each given connection configuration. Whenever a user
calls Open on a connection, the pooler looks for an available
connection in the pool. If a pooled connection is available, it
returns it to the caller instead of opening a new connection. When the
application calls Close on the connection, the pooler returns it to
the pooled set of active connections instead of closing it. Once the
connection is returned to the pool, it is ready to be reused on the
next Open call.
I'd open the connection, go through the loop as many times as needed, then close the connection. Opening and closing is very expensive. But, thanks to Mitch Wheat and Dave Markle, I've learned that connection pooling is done for free in the background with .NET, so the expense should be amortized over all your requests.
Even better, I'd batch the requests in the loop and execute the batch after the loop was done. You only require one network round trip that way.
If you agree with that last bit, I'd make sure that the batch INSERT was done in a transaction context so it could be committed or rolled back as a single unit of work. Isolation and thread safety will matter.
I personally would open and close the connection each time. You should be protecting your code in a way that any exception will ultimately close your connection. Will your app be the only application talking to this database?
Actually you must explicitly close SqlConnection.Open()
From MSDN, "Note If the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose."
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.71).aspx
Cheers!
Background info: I'm coding with C#, using Microsoft SQL Server for databases.
I didn't find much on Google on the subject, so I'm asking here: should I always close a connection to my database after performing a query?
I'm torn between two solutions (maybe better ones exist...):
either open the connection before querying, then close it right after the SQL query
or open the connection at the start of my application, and before each SQL query check if the connection is still up and reopen it if needed.
In the past, I used the first solution but I discovered that opening a new connection can take quite some time (especially over a VPN connection to my LAN opened through 3G), and that it would slow down my application. That's why I decided to go with the second solution (in that case, my connection should be always up if we forget about time-out) and noticed some better performances.
Do I need to close the connection at the end of my application or can I forget about it?
Yes, you should close your connection after each SQL query. The database connection pool will handle the physical network connection, and keep it open for you. You say that you found that opening a connection can take some time - did you find that the application was really doing that multiple times?
(I hope your real application won't be talking directly to the database over 3G, btw... presumably this is just for development purposes...)
One important thing to remember is that there is a unique connection pool for each unique connection string you use... so always use the same connection string unless you need to connect to a different database (or have unique requirements).
Here is a good document on connection pooling with System.Data.SqlClient.SqlConnection.
This will heavily depend on how many clients you anticipate will need to connect to the database. Leaving the connection open, could prevent another user from accessing the DB while they wait for an open connection.
I've got a few simple questions about connection pooling and best practices.
I'm planning and writing a small application which relies on a MySQL database. In this application I use modules and plug-ins which can create connections. The application has direct access to the MySQL database and it will probably be the only client connecting to the database.
Here are my first questions: Will connection pooling make sense? Is it irrelevant or should I disable it? What are your experiences?
On the other hand in my company we develop another software which has one MySQL database server and many clients. Every client can open multiple windows in which multiple connections can be active. There is a good chance that this software will be using the basic concept of my new application. The clients connect directly with the database. So I guess it would make a lot of sense to write a server application which handles the pooling and organizes the connections, am I right? How much sense would it make to let every client use it's own connection pool? We're talking about 1-50 clients with 1-10 connections.
Do you think it's the best to write a small server application to handle the connection pooling?
I'm asking because I don't really know when connection pooling makes sense and when not and how to handle it with small and medium sized client applications. I'm looking for some input of your experiences. :) I hope the questions is not to awkward. ^^
Greetings,
Simon
P.S.: It's a windows based application. Not a web service.
Connection pooling will give you extra performance, actually without it performance may be an issue even for a small application (it depends on the number of calls, data, etc).
Consider properly handling your connections in order to avoid 'max pool size reached' errors and timeouts. A good practice is to handle your connection like this:
using (SqlConnection conn = new SqlConnection(myConnectionString))
{
conn.Open();
doSomething(conn);
}
using guaranties than the connection will be properly closed/disposed. Check this article that provides some tips that can be applied either for MSSQL or MySQL.
Consider also the use of stored procedures. Hope this help you getting started.
When a connection to DB is opened using C# OPEN statement, does that impact the web server performance or only the Database?
So, how does the repeated opening and closing of the database connection impact the web server and the database.
Can somebody please give me some insight on this. Thanks.
Opening a database connection is a relatively expensive operation. Opening database connections can be so expensive that ADO.NET by default enables connection pooling. If you are not using connection pooling then your application is probably going to run slower (decreased response time) and could even hit problems with scalability.
If you are using connection pooling then repeated opening and closing of a SqlConnection does not incur the large overhead of creating a network connection, authenticating with SQL Server, setting any connection specific data (etc.) that occurs without pooling (except on the initial physical connection creation). When Open is called, an existing connection is retrieved from the pool (if available) and when Close is called then connection is returned to the pool.
With connection pooling enabled, I would expect to see a memory increase on both the web and database servers in maintaining the open connections. If you aren't using connection pooling, then you could do some tests to measure what the performance impact is to both servers.
Usually this isn't something you need to worry about — use connection pooling and tune the pool parameters if necessary.
It impacts end-to-end response time, because of stuff going on in both the database and the web server. In short, your web pages will all load more slowly, even under light load.
Throughput-wise, it probably hurts the database more, since it's doing all the authentication work, but that's just a wild guess.