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?
2 Answers
The answer to your first question is: yes. And no. You can use a lock block, or you can use a Mutex, 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.
1 Comment
lock is more lightweight, while a Mutex is an operating system object, that always requires a handle to be allocated from the kernel. The lock, or Monitor, only uses a kernel primitive (behind the scenes) when actually blocking and being contented, i.e. not getting the lock after a short spin-time. So in general, using a lock is most likely the better alternative, unless you need to have a lock spanning multiple processes.If you're updating single variables (and don't need more than one updated together as an atomic unit), I'd use the Interlocked class which provides lockless atomic functionality. If you have many threads all attempting to update those variables, Interlocked will help reduce contention.
http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx