.Net4, Monitor.Enter (lockObject, receivedLock)

In .Net4, Monitor.Enter (Object) is marked obsolete:

[ObsoleteAttribute("This method does not allow its caller to reliably release the lock.  Please use an overload with a lockTaken argument instead.")]
public static void Enter(
    Object obj
)

And there is a new Monitor.Enter method (lockObject acquired by Lock) with this use:

bool acquiredLock = false;

try
{
    Monitor.Enter(lockObject, ref acquiredLock);

    // Code that accesses resources that are protected by the lock.

}
finally
{
    if (acquiredLock)
    {
        Monitor.Exit(lockObject);
    }
}

I did it like this:

Monitor.Enter(lockObject);
try
{

    // Code that accesses resources that are protected by the lock.
}
finally
{
    Monitor.Exit(lockObject);
}

It is not right? What for? Maybe with interupt after login, but before trying?
As Eamon Nerbonn wrote: what happens if an asynchronous exception eventually occurs before monitor.exit?

Answer: ThreadAbortException

When this exception is raised, runtime executes all final blocks before terminating the thread.

+3
source share
1 answer

, , try.

, , finally , . ( , Monitor.Enter , .)

IIRC, lock .NET 4.0.

+5

Source: https://habr.com/ru/post/1720871/


All Articles