Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Another thread question

Posted on 2011-03-10
3
Medium Priority
?
208 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 86

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 86

Accepted Solution

by:
Mike Tomlinson earned 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

721 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