Yes your code will still work fine. There are however some huge
differences between this code and the original.

1) inlining will not be performed since you have put the lock in (this
will result in a (relatively) significant performance hit compared to
the original)
2) In some cases you will have a memory barrier
3) You don't need a critical section in this case (see explanation below)
4) You should be locking on a private lock object as opposed to
locking on "this"


An alternative which you should consider would be

 public sealed class MyClass
 {
    public MyClass(string strValue)
    {
       strMyField_ = strValue;
    }

    public string MyField
    {
       get
       {
             return strMyField_;
       }
    }

      volatile string strMyField_;
 }

This will inline properly and offers nearly identical behavior as your
first example without the overhead you are introducing with a critical
section. This can only be used on items that are the size of a
reference or smaller. The reason you can do this is that anything the
size of a reference or smaller is assured to be changed in an atomic
fashion where you would not need to actually define a critical
section. If the size is over the size of a reference you would then
need to lock in order to insure only one thread at a time is dealing
with the data.



On 8/10/06, Eddie Lascu <[EMAIL PROTECTED]> wrote:
I want to make my class multithread safe. What's the effect of writing
something like this:

  public sealed class MyClass
  {
     public MyClass(string strValue)
     {
        strMyField_ = strValue;
     }

     public string MyField
     {
        get
        {
           lock(this)
               {
              return strMyFieldId_;
           }
        }
     }

       string strMyField_;
  }

I know "lock" injects the "finally" block into the CIL, but is that executed
if the return is before?

===================================
This list is hosted by DevelopMentor(r)  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com



--
If knowledge can create problems, it is not through ignorance that we
can solve them.

Isaac Asimov

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to