Sreejith G
Sreejith G

Reputation: 211

lock statement and performance of Task Parallel Library

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?

Upvotes: 1

Views: 2142

Answers (2)

Kenneth Ito
Kenneth Ito

Reputation: 5261

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

Upvotes: 1

Dan Puzey
Dan Puzey

Reputation: 34200

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.

Upvotes: 1

Related Questions