multithreading - VB.NET Do I need multiple SyncLocks if I want to lock multiple things? -


vb.net 2010, .net 4

hello all,

my question is, imagine have 2 list(of t) objects , subroutine in multithreaded environment modifies both of these objects. don't understand locks well, i'm unsure whether can do:

synclock ctype(list1, ilist).syncroot    list1.clear()   list2.clear()  end synclock 

or must i:

synclock ctype(list1, ilist).syncroot   synclock ctype(list2, ilist).syncroot      list1.clear()     list2.clear()    end synclock end synclock 

? insight? on right track? comments appreciated.

thanks lot in advance, brian

first, bad practice lock on non-private object, else might lock on it, , things go downhill there, instead lock on private member object, like

class class1     private lockobject new object      public sub clear()         synclock lockobject            ...         end synclock     end sub end class 

now, actual question: unless every operation modifies both lists (doubtful), should have 1 lock per list. while possible use 1 lock object mean "i'm doing list", doesn't make sense block method in thread isn't operating on same list yours, , slow down everything.

so, in short: use 1 lock object per set of locks (locks operating on list1, locks list 2, etc). it's more code sections operate on both lists, code more performant.

also, general note: hold lock little time possible. less time spent in lock, less chance thread come along , blocked until you're done.

the msdn page on synclock might worth read, contains information , few examples. , @basiclife correct, make sure take locks in same order everywhere.

and general rule throughout framework, unless accessing static member on class, unless otherwise stated, not thread safe. when operating on lists, want lock when add, remove, clear or enumerate on list, i'm sure there's others, common.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -