tags:

views:

162

answers:

4

I have a method which has been called many times by other methods to hash data. Inside the method, some lock statements are used. Could you please let me know whether the lock statement is time-consuming and what is the best way to improve it.

P/S: I have been finding a way to avoid using the lock statement in this method.

+3  A: 

The lock statement itself is not very time-consuming, but it may cause contention over shared data.

Followup: if you need to protect shared data, use a lock. Lock-free code is wicked difficult to do correctly, as this article illustrates.

Stephen Cleary
+7  A: 

Your question is not answerable. It depends entirely on whether the lock is contended or not.

Let me put it this way: you're asking "does it take a long time to enter the bathroom?" without telling us how many people are already in line to use it. If there is never anyone in line, not long at all. If there are usually twenty people waiting to get in, perhaps very long indeed.

Eric Lippert
My situation is:- If the lock statement is not used, I have to pass a parameter to the method.- The lock rarely takes effect on some situations. In most case, the lock statement is not necessary. But for thread safety, we have to add the lock statement.Any suggestion?
Mark Attwood
It comes out to another question: Is using the lock statement more time-consuming than passing an object to the method?
Mark Attwood
@markattwood: The only person here who can measure the performance of your code on your hardware is you. Try it both ways, measure the results carefully and then you'll know.
Eric Lippert
+1  A: 

The lock statement itself is actually some syntactic sugar that creates and manages a Monitor object.

This in itself is usually not overly resource intensive, but can become a problem if you have multiple reads but no writes to your variable across multiple threads. Each read will have to wait for the other to finish before a read can complete. In scenarios where you might be getting the variable from multiple threads, but not setting it, you might want to look at using a ReaderWriterLockSlim object to manage asynchronous reads and writes.

Kevin McKelvin
Monitor is a static class, no instance will be created. But an additional SyncBlock is allocated by the CLR.
Henk Holterman
A: 

You might find this article on threads interesting and relevant. One of the claims that it makes is "Locking itself is very fast: a lock is typically obtained in tens of nanoseconds assuming no blocking."

Mike Chess
I will use the lock statement instead of parameters
Mark Attwood