Skip to content

Monitor.TryEnter sometimes fails even if Monitor.IsEntered returns true #76660

@ForNeVeR

Description

@ForNeVeR

Description

In a large code base, we have a snippet like this:

object myMutex = new object();

void Foo()
{
    if (Monitor.IsEntered(myMutex))
    {
        if (!Monitor.TryEnter(myMutex))
            LogError("Fail"); // #1
    }
}

Theortically, line #1 should never be visited, right? But we observe that it actually gets visited sometimes.

Initially, we weren't checking Monitor.TryEnter inside of Monitor.IsEntered, of course, and this code was added for diagnostic purposes after we've noticed deadlocks related to this piece of code: the thread holding the monitor was receiving false from Monitor.TryEnter, despite it should theoretically always succeed and return true.

Reproduction Steps

This was initially reported by the user of our product, and we were able to track it down to the described code.

We are occasionally able to trigger the code to enter this line locally, during a debug session, but so far were unable to prepare an isolated MCVE. We are able to share more code if this helps.

Expected behavior

Monitor.TryEnter should always succeed if the calling thread is holding the lock (i.e. if Monitor.IsEntered returns true).

Actual behavior

Monitor.TryEnter occasionally returns false despite the calling thread holding the lock (i.e. if Monitor.IsEntered returns true).

Regression?

No response

Known Workarounds

Replace a call to Monitor.TryEnter(myMutex) with the following block:

if (Monitor.IsEntered(myMutex))
  Monitor.Enter(myMutex);

Surprisingly, this works so far.

Configuration

  • .NET version: .NET 6.0.8
  • OS: Windows 10
  • Architecture: x64

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions