Click here to Skip to main content
16,022,413 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Say we have the following:
C#
private object _lock = new object();
public void A()
{
   lock(_lock)
   {
       // do something critical
       B();
   }
}

public void B()
{
   // do something else
}
And we call the A method from Tasks or Threads does the lock operation block cover the B method call also i.e. B calls are also serialized?

(I seem to have weird things going on which can only be explained by the B method not happening in the lock - or I could be mistaken).
Posted

1 solution

No. The method B is not covered.

The lock statement makes sure that when two callers call A, one of the executes B and completes before the other one starts execution (of the code within the lock statement).

B could actually be called from anywhere else in the application (not by calling A) and there would be nothing stopping from executing it!
 
Share this answer
 
v2
Comments
Mehdi Gholam 15-Mar-12 5:45am    
B is only being called from A and not directly. B is actually a filestream write and I am getting corrupt data in the stream.
Abhinav S 15-Mar-12 5:59am    
Sounds strange but why don't you move the lock around B and give it a try? Sometimes strange things work! :)
Mehdi Gholam 15-Mar-12 6:08am    
I have, it's the same. Maybe my read and write streams are out of sync?
Abhinav S 15-Mar-12 7:04am    
Possibly.
Mehdi Gholam 16-Mar-12 3:45am    
Found the bug, it was the stream flushing, I removed it and it works fine now.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900