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 ..

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.