2 strategies from the top of my head:

1:
    if (bNeedInit)
    {
        lock(this)
        {
            if (bNeedInit)
            {
                <init stuff>
                bNeedInit = false;
            }

    ....

2:
    public myClass()
    {
        <init stuff>
        ...

The second one is interesting in whether other threads could access an
uninitialized class, but as long as you don't do special things like start
threads in your base classes, you should be allright.

-- Henkk

----- Original Message -----
From: "Anand Ranganathan" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Friday, April 26, 2002 3:10 PM
Subject: [DOTNET] lock - how expensive is it to call?


> Hi I have a class as follows
>
> class myClass
> {
>    private ArrayList SomeArray;
>
>    public ArrayList SomeThing
>    {
>      get
>      {
>       lock(SomeArray)
>       {
>          if (SomeArray.Count == 0)
>           //initialize
>       }
>       return SomeArray;
>      }
>    }
> }
>
> Now I call my SomeThing property all over the place in
> my code. I put a counter inside my lock block and
> found that my lock statement is getting called over
> 300,000 times! My question is is there a better way to
> thread safely intialize my array without having to get
> a lock everytime I want to access the property. Is the
> process of just getting a lock expensive? I am not so
> much concerned over how many threads are going to
> block on the lock as I don't expect high contention.
> but I am not sure how much performance I am losing by
> locking and releasing locks so many times. Can someone
> suggest a better way to thread safely intialize my
> array member.
>
> __________________________________________________
> Do You Yahoo!?
> Yahoo! Games - play chess, backgammon, pool and more
> http://games.yahoo.com/
>
> You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
> subscribe to other DevelopMentor lists at http://discuss.develop.com.
>

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to