Search code examples
c#locking

Is the "lock" statement in C# time-consuming?


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.


Solution

  • 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.