Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

c# - Guidelines of when to use locking

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best guide for locking and threading I found, is this page (this is the text I consult when working with locking and threading):

http://www.albahari.com/threading/

You want the paragraph "Locking and Thread Safety", but read the rest as well, it is very well written.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...