Search code examples
c#multithreadinglocking

Local C# lock for a method?


All the tutorials/examples I have seen regarding C# lock are using a class member variable for locking.

Instead of using a class member variable, I want to use a local variable for locking the execution of a particular section of the code.

My Sample Code:

class TestClass
{
    public static int TestMethod()
    {
        // some code
        
        foreach (var example in Examples)
        {
            //some code...
            
            object myLock = new object(); // QUESTION: Is this valid?
            Parallel.ForEach(AllChunks, (chunk) =>
            {
                // some code...
                
                lock(myLock)
                {
                    // do some GPU related activities
                }
            }
        }
        
        return 0;
    }
}

In the above code, I am using myLock (a local variable inside TestMethod()) to lock the execution of a particular section of the code.

QUESTION: Is this implementation valid and correct? My lock is not readonly (as suggested in tutorials).


Solution

  • Yes, it's perfectly fine.

    (Sorry this answer is so short, but there is nothing else to say really)