Using Monitor Class

Posted by Mubashar Ahmad on Stack Overflow See other posts from Stack Overflow or by Mubashar Ahmad
Published on 2010-03-24T05:35:17Z Indexed on 2010/03/24 5:43 UTC
Read the original article Hit count: 689

Filed under:
|
|

Dear All

I would like to ask couple of Questions regarding the use of Monitor Class in .Net.

To understand the Questions please look at the following Code.

public class MyClass
{
    private List<int> _MyCollection = new List<int>();

    public void GetLock()
    {
        Monitor.Enter(_MyCollection);
    }

    public void ReleaseLock()
    {
        Monitor.Exit(_MyCollection);
    }

    public void UpdateCollection(/*anyparam*/)
    {
        //update collection without lock on collection
    }
}

public class MyAppMain
{
    private static MyClass myclass = new MyClass();

    public static void main(args)
    {
        try
        {
            myclass.GetLock();

            //an operation that does not do any update on myclass but wanted 
            //to ensure that the collection within myclass never update
            //while its doing following opetion

            //Do somthing
        }
        finally
        {
            myclass.ReleaseLock();
        }
    }
}

Now is this the right use of monitor and do i need to use Pulse or PulseAll to signal waiting thread and if so than should use plus before or after Exit function?

Regards Mubashar

© Stack Overflow or respective owner

Related posts about .NET

Related posts about synchronization