Solved

Another thread question

Posted on 2011-03-10
3
200 Views
Last Modified: 2012-05-11
My question is around locking objects. I'm not clear when it is necessary and when it isn't in my particular case.

I have a loop that loops through a lst of vendors (see code below).

I also have a eventhandler that tells me when the thread is finished. I update the vendors last update dates and set it to CanStart = true.

My question is do I need to use the lock in the for loop where I'm starting the threads as well as what I'm doing in the event handler?

I just don't want to run into a locked condition.


For Each v In lstVendors
                If blnStopAllThreads = False AndAlso v.CanStart = True AndAlso _
                   UpdateQueue.Count > 0 AndAlso intUpdateThreadCnt < MaxUpdateThreads Then
                    v.CanStart = False
                    'Create a new thread
                    intUpdateThreadCnt += 1
                    Dim UThread As New UpdateThread("UpdateThread - " & CStr(intUpdateThreadCnt))
                    UThread.MyVendor = v
                    AddHandler UThread.ThreadCompleted, AddressOf UpdateThreadCompletedEventHandler
                    AddHandler UThread.ThreadVendorUpdated, AddressOf UpdateThreadVendorLastUpdateChangedEventHandler
                    Dim MyThread As Thread = New Thread(AddressOf UThread.UpdateData)
                    MyThread.Priority = ThreadPriority.Normal
                    MyThread.Name = "UpdateThread - " & CStr(intUpdateThreadCnt)
                    lstUpdateThreads.Add(MyThread)
                    MyThread.Start()
                End If

            Next








 Private Sub UpdateThreadVendorLastUpdateChangedEventHandler(ByVal v As Vendor)
        Dim i As Integer
        'LogOps.LogMessage("INFO", "ThreadVendorLastUpdateChangedEventHandler-ThreadCompletedEvent", "In Update Changed Event Handler")
        Try
            boolMonitorEntered = Monitor.TryEnter(MySyncLock, 15000)
            boolLockCreated = True

            If boolMonitorEntered Then
                For i = 0 To lstVendors.Count - 1
                    If lstVendors.Item(i).ForeignSysExchangeId = v.ForeignSysExchangeId Then
                        lstVendors.Item(i).LastAllergyUpdateDate = v.LastAllergyUpdateDate
                        lstVendors.Item(i).LastMedUpdateDate = v.LastMedUpdateDate
                        lstVendors.Item(i).LastRxUpdateDate = v.LastRxUpdateDate
                        lstVendors.Item(i).CanStart = True
                        Exit For
                    End If
                Next
            End If
        Finally
            If boolLockCreated = True Then
                Monitor.Exit(MySyncLock)
            End If
        End Try
    End Sub

Open in new window

0
Comment
Question by:rutledgj
  • 2
3 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35102274
Whether the lock is necessary or not depends on if more than one thread can ever satisfy this condition in your update handler at the same time:

    If lstVendors.Item(i).ForeignSysExchangeId = v.ForeignSysExchangeId Then

If more than one thread can end up matching the same "record" then you do need the lock if you wish to prevent them both writing to the same record and possibly only doing a partial update as they step on each other.

If every single thread will always be updating a unique record then the lock is not necessary.

One thread for every record is probably not a good approach though...  =\
How many are we talking about here?

A ThreadPool might be a better design.
0
 

Author Comment

by:rutledgj
ID: 35102615
Each thread operates on a single unique vendor which can contain any number of customers. My question isn't about having a lock in the eventhandler but in the for loop where I'm assigning the vendors to the threads.
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 35102717
Gotcha...no, you should not need a lock up there.

A different issue, though, is that you are using a For Each iterator in the starter and possibly modifying that collection in the update handler.  If the update handler is fired before all the threads are started it could cause an issue.

Using an indexed for loop in both places would probably fix that if the issue arises.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now