80

I am using an instance of ManualResetEvent to control thread access to a resource but I'm running into problems with it. Does anyone know how I can find out during debugging what the state of the object is?

That is to say I would like to know if the ManualResetEvent is currently blocking any threads and maybe even how many and which threads it is blocking.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
George Mauer
  • 117,483
  • 131
  • 382
  • 612
  • 25
    Just for the record, on .NET 4 one can now use `ManualResetEventSlim`, which, among other things, provides an `IsSet` method that is [said to be](http://download.microsoft.com/download/B/C/F/BCFD4868-1354-45E3-B71B-B851CD78733D/PerformanceCharacteristicsOfSyncPrimitives.pdf) faster than `WaitOne(0)`. – Roman Starkov Nov 22 '10 at 15:34

3 Answers3

103

Perform a WaitOne on the event with a timeout value of zero.

It will return true if the event is set, or false if the timeout occurs. In other words, true -> event is set, false -> event is not set.

Andrew Rollings
  • 14,340
  • 7
  • 51
  • 50
  • 2
    Thats a good idea, the debugger allows me to check its internals though, can't I find the state somewhere in there? – George Mauer Dec 23 '08 at 15:56
  • 1
    Hmm... Dunno. I seem to recall that it's an opaque object and not much help to look at. However, you can probably execute the WaitOne call in the Immediate Window during debugging :) – Andrew Rollings Dec 23 '08 at 15:57
  • 1
    You cannot check the internals because this class is a wrapper around an OS construct that is represented only by a handle. – Kent Jun 21 '18 at 06:18
  • What to do when WaitOne evaluation fails with "Cannot evaluate expression because the code of the current method is optimized." (on chk build!) – David Burg Apr 15 '19 at 20:46
  • Store the return value in a variable and/or use System.Diagnostics.Debug.Write and set the breakpoint just after? – Andrew Rollings Apr 17 '19 at 01:19
8

Here is working code:

private ManualResetEvent pause = new ManualResetEvent(false);
pause.WaitOne(); // caller thread pauses
pause.Set();    // another thread releases paused thread

// Check pause state
public bool IsPaused { get { return !pause.WaitOne(0); } }
fab
  • 2,479
  • 1
  • 16
  • 6
  • 1
    At least call it `IsBlocking`. I don't see how this enhances the given answer, I guess we can write down `WaitOne(0)` itself given the answer "Perform a `WaitOne` on the event with a timeout value of zero." – Maarten Bodewes Jul 26 '18 at 11:49
1

You can make function calls in the Debugger Watch window. Add a call to mreVariable.WaitOne(0) in the Watch window and see what it evaluates to. Note: You should not use this for AutoResetEvents since that could change the actual state.