4

Are the c# ManualResetEvent and AutoResetEvent classes expensive to create or to maintain?

Do they consume some kind of limited Windows kernel resources, and if so, how limited is it?

E.g. if I have code that can create a new AutoResetEvent every 100ms (to be disposed shortly afterwards), should I worry about putting old AutoResetEvents in a pool and reusing them, or is that not a significant concern?

Since they are IDisposables, I presume they consume some sort of limited resource. Just how much do they consume, and at which point should I start worrying about using too many of them?

The fact that there is a ManualResetEventSlim, but no AutoResetEventSlim also worries me a bit.

HugoRune
  • 13,157
  • 7
  • 69
  • 144
  • I would advice an alternative design that does not need all those dynamic events being created. – Philip Stuyck Aug 20 '15 at 16:55
  • Thank for the advice, this would be my intuitive understanding as well. Why would you advice that though? What exactly are the hidden costs of creating these events dynamically? – HugoRune Aug 20 '15 at 17:01
  • It is based on experience in embedded systems. Usually threads, and thread synchronisation objects are all created upfront. – Philip Stuyck Aug 20 '15 at 17:03
  • This very strongly fits the "If you need to know then you are doing it wrong" category. The limit is far, far beyond the point where you completely lost control over the threading in your program. Depends on maximum paged kernel memory pool size, millions. – Hans Passant Aug 20 '15 at 17:25

1 Answers1

1

ManualResetEvent uses Wait Handles whereas ManualResetEventSlim uses Busy Spinning

The best performance, in order, is: 1) standard locking (Monitor) 2) "slim" event classes 3) standard event classes

Given your use case, I would recommend using the "slim" classes, since you will only be waiting for a short amount of time. Also, if a "slim" class waits for too long, it behaves as a "non-slim" class anyway.

Note you cannot use the "slim" classes across processes.


EDIT: This is why AutoResetEvent does not have a "slim" version - basically it's because the wait times of AutoResetEvent are typically longer than ManualResetEvent, so it isn't appropriate to use "busy spinning"


EDIT: A wait handle inherits from MarshalByRefObject. Ultimately .NET runtime sets up a proxy (TransparentProxy class) for remote access to your wait handle.

See here and here for more information.


Community
  • 1
  • 1
djrecipe
  • 90
  • 10
  • 2
    What resources does such a WaitHandle as used by AutoResetEvent or ManualResetEvent consume though? Given that ManualResetEventSlim behaves as ManualResetEvent for longer wait times, I presume that the resource consumption is also similar for those wait times. – HugoRune Aug 20 '15 at 17:05