Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
The lock Statement | Threading
Advanced C# with .NET
course content

Зміст курсу

Advanced C# with .NET

Advanced C# with .NET

1. Introduction to Desktop Development with .NET
2. Interactive GUI
3. Threading
4. Generics & Reflection

book
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:

cs

index

copy
1234
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:

1. What is the purpose of the lock statement in C#?
2. Which keyword is used to define a critical section of code protected by a lock?
What is the purpose of the lock statement in C#?

What is the purpose of the lock statement in C#?

Виберіть правильну відповідь

Which keyword is used to define a critical section of code protected by a lock?

Which keyword is used to define a critical section of code protected by a lock?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt