11 April 2017

How lock(obj) Method Works

I once had a requirement to generate a random integer number from let's say 0 to 10 million. Here's what I did:

public static int GetRandomNumber(int min, int max)
{
    lock (obj)
    {
        //some codes for calling Random method is omitted for brevity      
    }
}

I used lock statement to ensure that the object was locked by the first thread and released the object first before another thread to lock the same object.

I think lock is more concise that using a monitor class in blocking the thread.


No comments:

Post a Comment