1

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?

1
  • 1
    Posting some example code would help get answers for this. Commented Apr 23, 2012 at 15:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Regarding your first statement: actually a 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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.