Hello All,
I have a question regardind=g accessing shared resources.

I have a for loop in which i am creating many threads..

And each thread at some point of time they call this function :

Public Function UpdateMailJobs(ByVal con As Data.DataRow, ByVal jobid As String, ByVal varName As String, ByVal value As String) As Boolean
        mutJob.WaitOne()
        Dim connection As New SQLManager.cls_SQLManager
        connection.ConnectionString = CstrG(con("ConnectionString"))
        connection.CommandText = "UPDATE MailJob SET " & varName & " = " & value & " Where JobID=" & jobid
        registerError(con, "MailJob table update(updatemailjobs-fn1) finished(" & jobid & ")")
        Try
            connection.ExecuteNonQuery()            
        Catch ex As Exception
            mutJob.ReleaseMutex()
            Return False
        End Try
        mutJob.ReleaseMutex()
        Return True
    End Function

But i am not very sure weather this is correct or not ( Regarding the mutex i have used) . Can any one please advice ? Will this work perfectly even if there are 10 threads runinng at the same time ? Thanks in advance ..

Dani AI

Generated

As 's snippet shows, a mutex will serialize access and can work — but there are a few real risks and better alternatives worth applying.

Always guarantee release. If an exception is thrown before you release the mutex you will deadlock other threads; wrap WaitOne/ReleaseMutex in Try...Finally so the mutex is always released:

mutJob.WaitOne()
Try
    ' perform the update work
Finally
    mutJob.ReleaseMutex()
End Try

Prefer in-process monitors. If synchronization is only inside your process, SyncLock (Monitor) is lighter and the compiler emits the try/finally for you. Use a private Shared lock object (do not lock on Strings, Me, or Type objects). Use Mutex only when you need cross-process coordination.

Don’t serialize DB updates unless you must. Let the database manage concurrency (row-level locks, transactions, optimistic concurrency) and avoid turning every update into a single-thread bottleneck. Also avoid building SQL by concatenation: validate any dynamic column names against a whitelist and always use parameterized commands for values. Example pattern (validate column name, then parameterize):

Dim allowed = New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) From {"Status","LastRun","Attempts"}
If Not allowed.Contains(varName) Then Throw New ArgumentException("Invalid column")
Dim sql = String.Format("UPDATE MailJob SET [{0}] = @value WHERE JobID = @jobid", varName)
' Use Using blocks for connection/command and add parameters for @value/@jobid

If you spawn many threads in a loop, consider using the ThreadPool/Tasks or throttle concurrency with SemaphoreSlim (limit N concurrent DB writers) rather than thousands of raw threads. These patterns keep your app responsive and avoid overwhelming the database while still allowing safe parallelism.

Recommended Answers

All 3 Replies

Quick answer ( I can give more detail tonight if needed ):

Look into SyncLock

So, is the use of mutex wrong ?

I don't know if using Mutex is wrong or not... I've never had to use it.

I've written several multi-threaded applications and when it comes to avoiding crossthreading in Shared Classes this is the only way I've done it.

So lets say I have a class ( clsDoSomeWork ) that will be our threads. And clsDoSomeWork as a method ( DoItNow( Name, Time) that we call to start each thread.

Public Class clsDoSomeWork

'This is our lock object
Private Shared objWorkLock as New Object

'This is our starting point for each thread
Public Sub DoItNow(ByVal strName as String, ByVal dtTime as DateTime)


'Here we would have some code that isn't going to access methods on other threads.
'For Example
For i as Integer = 1 to 5
   strName = String.Concat(strName, i.ToString)
Next 

'Now we have code that accesses a public variable or method on another thread.
'So we lock it down.
SyncLock objWorkLock

'Do some stuff like save data or write to the registry, etc.

End SyncLock

End Class
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.