从同一线程多次调用 sub

calling sub multiple times from same thread

我有一个单线程应用程序,需要多次调用子程序,每次都传递不同的参数。唯一的问题是子程序打开数据 reader 并从数据库中读取数据(使用传递的参数)。这工作正常,但读取操作需要几秒钟,所以第二次调用 sub 会抛出错误 "there is already an open datareader associated with this connection"。

在不重新设计我的整个应用程序的情况下,我是否遗漏了一些我需要对数据进行处理的地方reader以允许同时进行多个读取?

谢谢。

例如:

For x as integer = 0 to 10
 dim id as integer = my_sub(x)
Next X

Private function my_sub(x)

  dim return_value as integer = 0

  my_reader = sqldatareader
  db.cmd.CommandText = "select id from database where id = " & x
  my_reader = db.cmd.ExecuteReader
  my_reader.Read()
  If my_reader.HasRows Then
     return_value = my_reader(0)
  End If
  my_reader.Close()

  Return return_value

End Sub

用户HardCode provided a great explanation in

Your Command, and presumably your Connection, are not scoped to the my_sub(). You should be instantiating your connection and command objects as they are needed, and then dispose of them. Yours are already instantiated (and the connection open), wrapped in variable db. This is what is causing the problem.

对应的代码是这样的

Private Function MySub(x As Integer) As Integer

    Dim returnValue As Integer = 0

    Using conn As New SqlConnection(yourConnectionString)
        Dim sql = "SELECT [id] FROM [database] WHERE [id] = @x"

        Using cmd As New SqlCommand(sql, conn)
            cmd.Parameters.Add(New SqlParameter With {.ParameterName = "@x", .SqlDbType = SqlDbType.Int, .Value = x})

            conn.Open()
            Dim rdr = cmd.ExecuteReader()

            If rdr.HasRows Then
                rdr.Read()
                returnValue = rdr.GetInt32(0)
            End If

            rdr.Close()
            conn.Close()

        End Using
    End Using

    Return returnValue

End Function