O'Reilly logo

C# Multithreaded and Parallel Programming by Rodney Ringler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Locking resources to ensure thread-safe data

So far we have chosen to design our application in a manner so that there is no need to lock resources to protect them from being "stomped" on by other threads, thereby causing race conditions and other unexpected behavior.

The lock syntax is as follows:

                        lock (objVariable)
                        {
                            
                        }

The code between the brackets is executed in a thread-safe manner and will not let other threads operate on the object being locked until the lock execution is completed.

Other threads that try to perform an operation on an object that is locked will wait until the lock is freed before they continue their operation on the object. This is important to note because it can create "locking" issues where one thread is waiting on a resource ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required