Guidelines of when to use locking

Posted by miguel on Stack Overflow See other posts from Stack Overflow or by miguel
Published on 2010-05-06T08:48:15Z Indexed on 2010/05/06 8:58 UTC
Read the original article Hit count: 302

Filed under:
|
|

I would like to know if there are any guidelineswhich a developer should follow as to when (and where) to place locks.

For instance: I understand that code such as this should be locked, to avoid the possibility of another thread changing the value of SomeHeapValue unexpectedly.

class Foo
{
  public SomeHeapObject myObject;
  public void DoSummat(object inputValue_)
  {
    myObject.SomeHeapValue = inputValue_;
  }

}

My question is, however, how deep does one go with the locking? For instance, if we have this code:

class Foo
{
  public SomeHeapObject myObject;
  public void DoSummat(object inputValue_)
  {
    myObject.SomeHeapValue = GetSomeHeapValue();
  }

}

Should we lock in the DoSummat(...) method, or should we lock in the GetSomeHeapValue() method?

Are there any guidelines that you all keep in mind when strcturing multi-threaded code?

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading