Sobes.tech
Middle

Kas saab kasutada stringi objektiina lukustamiseks lock-struktuuris?

sobes.tech AI

Vastus AI-lt

It is not recommended to use a string as a lock object in C#. Although technically possible, strings in .NET are immutable and can be interned, meaning that identical string literals may refer to the same object in memory.

This poses a risk that different parts of the program may accidentally use the same string for locking, leading to unpredictable behavior and synchronization issues.

The correct approach is to use a separate private object for locking:

private readonly object _lockObj = new object();

lock(_lockObj)
{
    // critical section
}

This ensures that the lock is controlled only by your code and does not overlap with other parts of the program.