Click here to Skip to main content
12,625,447 members (36,564 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#
Say we have the following:
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 15-Mar-12 0:11am

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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!
  Permalink  
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.
Abhinav S 16-Mar-12 9:45am
   
Cool.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.161128.1 | Last Updated 15 Mar 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100