Hello,
I've been put in charge of making a lot of old ASP.NET 2.0 code thread safe after we started experiencing concurrency problems, particularly with database inserts. I've spent a lot of time searching and reading tutorials on the topic, but most of it is still going over my head. Nevertheless, I've put together a few functions to handle database updates, ex)
What I'd like to know is will this code be thread-safe as it is? Will it solve the concurrent database write problems? Am I right to be putting the locking object in an instance class?
Or am I horribly misinterpreting what I've read?
I've been put in charge of making a lot of old ASP.NET 2.0 code thread safe after we started experiencing concurrency problems, particularly with database inserts. I've spent a lot of time searching and reading tutorials on the topic, but most of it is still going over my head. Nevertheless, I've put together a few functions to handle database updates, ex)
VB.NET:
Public Class Podcast
. . .
Public Sub Insert_Podcast()
Dim stick As New Object()
SyncLock stick
If me.ID = 0 Then
Using conn As New SqlConnection(strConnection)
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
Dim trans As SqlTransaction = conn.BeginTransaction("Add_Transaction")
cmd.Connection = conn
cmd.Transaction = trans
Try
cmd.CommandText = Add_Podcast
cmd.Parameters.AddWithValue("@TITLE", me.title)
cmd.Parameters.AddWithValue("@FILENAME", me.filename)
cmd.Parameters.AddWithValue("@DESCRIPTION", me.description)
cmd.Parameters.AddWithValue("@VIEWS", me.views)
cmd.Parameters.AddWithValue("@LENGTH", me.length)
cmd.Parameters.AddWithValue("@SIZE", me.size)
cmd.Parameters.AddWithValue("@FORMAT", me.format)
cmd.Parameters.AddWithValue("@AUTHOR", me.author)
cmd.Parameters.AddWithValue("@RECORDED", me.recorded)
If cmd.ExecuteNonQuery() > 0 Then
cmd.CommandText = Get_New_ID
me.ID = CType(cmd.ExecuteScalar(), Integer)
End If
trans.Commit()
Catch Ex As Exception
trans.RollBack()
End Try
End Using
End If
End SyncLock
End Sub
. . .
End Class
What I'd like to know is will this code be thread-safe as it is? Will it solve the concurrent database write problems? Am I right to be putting the locking object in an instance class?
Or am I horribly misinterpreting what I've read?