title: .NET, the SqlConnection object, and multi-threading
body: <p>We have an application which uses an SQL Server 2008 R2 database. Within the application, calls to the database are made using a <code>SqlConnection</code> object.</p>
  
  <p>This <code>SqlConnection</code> object is initialized once, the first time it is accessed, and then re-used throughout the application. The action that we use is the following:</p>
  
  <pre><code>Protected _cn As SqlConnection = Nothing
  
  ...
  
  Protected Sub Open()
      If _cn Is Nothing Then
          _cn = New SqlConnection(_sqlConn)
      End If
  
      If _cn.State = ConnectionState.Closed OrElse _cn.State = ConnectionState.Broken Then
          _cn.Open()
      End If
  End Sub
  </code></pre>
  
  <p>This works perfectly fine during normal execution of the program. However, there are a few portions of the application that are executed in a multi-threaded fashion. When one of these parts is executing, frequent errors occur if other actions are made.</p>
  
  <p>After digging a bit, I realised that this is because there were times where two different threads both attempted to use the same <code>SqlConnection</code> object.</p>
  
  <p>So, after identifying the problem, I now need to find solutions. The obvious solution is to just re-create the <code>SqlConnection</code> object every time a database call requires one - in this case, it would never be shared. Is there any reason <em>not</em> to do this? I assumed originally that we had only one connection object per session of the application for performance reasons, but is this actually the case?</p>
  
  <p>If we do need to keep just one connection object open, what is the suggested solution? Should I put in place some sort of timer which will keep cycling until the connection object is available, and then access it?</p>