title: Sql connection in a windows service
body: <p>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.</p>
  
  <p>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)</p>
  
  <p>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.</p>
  
  <p>Just wondering if this is a bad idea?</p>
  
  <p>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?</p>
  
  <p>I was going to make a fault tolerant connection like this:</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>so if some reason the existing connection is closed or faulted in some way we would get a new open one</p>
  
  <p>is that bad design for any reason?</p>