How do I deal with “An attempt has been made to fr

2020-05-03 13:08发布

问题:

I know this question might be duplicate questions but I have a problem and need a solution to overcome it.

I've made a project and used functions and Sub everywhere.

One of the function/Sub is like,

Public Sub ExecuteQuery(Xcn As OleDbConnection)
    Try
        If Xcn.State = ConnectionState.Open Then Xcn.Close()
        Xcn.Open()
        cmd.Connection = Xcn
        cmd.ExecuteNonQuery()
        Xcn.Close()
    Catch e As Exception
        Throw e
    End Try
End Sub

I just use executequery(con) instead of writing whole sentence everytime.
Now the question is that I created a bw_worker and running a sub that includes small subs like I showed above asynchronously.

For example, A sub is that I run async like,

Private Sub RunCode()
    dim cmd as new oledbcommand("Select * from table",con)
    if con.state = ConnectionState.closed then con.open()
    execute reader stuff here
    if con.state = ConnectionState.Open then con.close()
    ExecuteQuery(con)
    cmd = new Oledbcommand("Select * from Table2",con)
    ExecuteQuery(con)
End Sub

I don't know if its good practice or not but now problem arises.
I am trying to create a loading screen for some time taking functions and subs so I referred this Link and faced the error.
NOTE: I understood the error it gives but I want to know a workaround if possible. Like something possible without changing a lot of code.

回答1:

If you keep your database objects local they won't be open on another thread. Commands too. This code will demonstrate how to use Using blocks which will close and dispose of your database objects even if there is an error. Please no .AddWithValue. The .Add method forces you to name a datatype which will help with visually providing a clue that the datatype passed in matches. There are also several database reasons to use .Add. See https://www.dbdelta.com/addwithvalue-is-evil/ and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

It is okay to have a class level variable for the connection string so you don't have to type it all the time.

Private ConnString As String = "Your connection string"

Private Sub RunCode()
    Using con As New OleDbConnection(ConnString)
        Using cmd As New OleDbCommand("Select * from table", con)
            con.Open()
            Using reader = cmd.ExecuteReader
                'reader stuff here
            End Using
        End Using
    End Using
End Sub


标签: vb.net