using lock statement to synchronise static variable access

Hi,
I am using framework 1.1
I have a static volatile bool variable in a class Globals

public class Globals
{
static volatile bool _bDoLiveUpdate;
public static bool DoLiveUpdate
{
get{return _bDoLiveUpdate;}
set{_bDoLiveUpdate = value;}
}
}


I have 2 more classes, one of which runs on a separate thread. Both these classes access the property Globals.DoLiveUpdate to perform certain functionality. How can I synchronise access to Globals.DoLiveUpdate by following two classes using lock Please note that the property Globals.DoLiveUpdate and variable _bDoLiveUpdate are both static while the class Globals is not declared static.

public Class ClassSameThread
{
MyFunc()
{
Globals.DoLiveUpdate = false;
// Do Something
Globals.DoLiveUpdate = true;
}
}

public Class ClassNEWThread
{
MyFunc()
{
if (!Globals.DoLiveUpdate)
{
Do Something
}
}
}


Thanks,




Answer this question

using lock statement to synchronise static variable access

  • chrstdvd

    Simply with the "lock" keyword, like this :

    public Class ClassSameThread

    {

    MyFunc()
    {
    lock(Globals)
    {

    Globals.DoLiveUpdate = false;

    // Do Something

    Globals.DoLiveUpdate = true;
    }

    }

    }

    public Class ClassNEWThread

    {

    MyFunc()

    {

    lock(Globals)

    {

    if (!Globals.DoLiveUpdate)

    {

    Do Something

    }

    }

    }

    }


    Warning : "lock" lock the entire object, if you want to lock only your property "DoLiveUpdate", you should use Mutex synchronization.


  • using lock statement to synchronise static variable access