Conteúdo do Curso
Advanced C# with .NET
Advanced C# with .NET
The lock Statement
When working with multiple threads, there can be situations where multiple threads are trying to access and update one resource at the same time. A resource can be anything, for-example a variable, a file, or even a remote resource which is being accessed through an API.
Such situations are called "race conditions" because whenever the threads usually race for the same resource and modifying the same resource at the same time can lead to unpredictable and inconsistent results.
We can ensure that there are no race conditions in our application by enclosing the code in lock
statements wherever it's expected that multiple threads might try to execute those statements at once.
In case multiple threads try to access a resource or execute a piece of code enclosed in a lock
, they are enqueued in a queue and forced to access the resource one by one, effectively eliminating any chance of a race condition.
The syntax for a lock statement is:
index
object keyObject = new object(); lock(keyObject) { // code to execute }
Here keyObject
is an instance of the object
class, and it serves as a key which ensures synchronization between multiple threads. This object should be the same for all the threads so it's usually a good practice to make it either a static member or make it accessible to all the threads without any change.
The following video demonstrates the usage of the lock statement:
Obrigado pelo seu feedback!