vb.net question about using db connections with threads

If I have a simple class

public class MyClass
       private myConn as new sqlconnection
       private MyThreadPool(5) as Thread

       public sub New()
          dim x as integer
          for x = 0 to 4
               MyThreadPool(x) = New THread(Addressof MyFunction)
        end sub

        private sub MyFunction()
              'Do some work in db
         end sub
end class

Is it safe for all of my threads to use the single instance declared at the class level or do I need to declare one within the MyFunction so each thread has its own instance?

Also, should the connection be opened and closed constantly or just opened once and left open while the thread runs?  The threads will pretty much run constantly.

Who is Participating?
carlnorrbomConnect With a Mentor Commented:

You should be able to share the instance cross the threads. I would suggest doing a check in the MyFunction similar to:
    Private Sub MyFunction()
        If Not myConn.State = Data.ConnectionState.Open Then
        End If
            'Do some work in db
        Catch ex As Exception
            'Manage exception
            'Clean up
        End Try
    End Sub

Open in new window

Also, not sure what happens if you were to call "MyConn.Close()" inside MyFunction while another thread was still executing so wouldn't recommend that.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.