In a C# 4 application I use a task parallel library for processing web request in parallel.After getting the web response there is a need to update some global variables, I decided to add a lock block to update that variables. Is the lock statement is best option to obtain mutual exclusion? and what is the exact relation between number of lock statements(or size of lock block) in TPL and performance decrease of TPL?
Share
The answer to your first question is: yes. And no. You can use a
lockblock, or you can use aMutex, there is little practical difference (within the context of a single application).The answer to your second question is: there is no exact relation. You could have a million locks, but the performance will only decrease if they are blocking eachother, and will decrease dependant on how much they block. (Caveat: the act of locking in itself will incur a performance penalty.)
The exact profile of your code will determine what the relationship is, and that will only really be known by running some tests and finding out.