Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Help needed to understand Monitor.TryEnter (Object, TimeSpan)

$
0
0

I believe I have fundamental misunderstanding of how Monitor.TryEnter (Object, TimeSpan) works.  This is best explained by the following code:

private async Task MethodAAsync()
{
  if (Monitor.TryEnter(oLock, TimeSpan.FromMilliseconds(10000)))
  {
    Debug.WriteLine("Start A");
    ...
    Debug.WriteLine("End A");
  }
}


private async Task MethodBAsync()
{
  if (Monitor.TryEnter(oLock, TimeSpan.FromMilliseconds(10000)))
  {
    Debug.WriteLine("Start B");
    ...
    Debug.WriteLine("End B");
  }
}

I though the following output should never occur, but it is actually occurring:

Start A

Start B

...

End A

I am omitting try-catch blocks in the above code.

I am trying to prevent MethodBAsync() from running any code during the execution of  MethodAAsync().   Could anyone kindly point out my misunderstanding?


Hong


Viewing all articles
Browse latest Browse all 31927

Trending Articles