app.cs
P/Invokes GetStdHandle()
and DuplicateHandle()
(among others), to do the following:
- Get the handle for standard output.
- Wrap (1) within a
SafeFileHandle
. - Duplicate (1) into a new
SafeFileHandle
instance. - Check the
SafeHandle.IsClosed
andSafeHandle.IsInvalid
properties. Close()
theSafeFileHandle
from (3)- Check the
SafeHandle.IsClosed
andSafeHandle.IsInvalid
properties.
The result is in app.txt
.
What it shows is that Close()
ing a SafeHandle
does not invalidate the handle. The handle continues to be valid, as far as SafeHandle.IsInvalid
is concerned.
Which means that to sanely use a SafeHandle
instance, both if the IsClosed
and IsInvalid
properties must be used, otherwise a closed handle may be used:
// BAD
if (handle.IsInvalid)
return;
// GOOD
if (handle.IsClosed || handle.IsInvalid)
return;