WindowsIdentity is IDisposable.
Recently I went on a quest to dispose of IDisposable objects wherever I could find them, since many types are IDisposable but people are not aware of this fact. (Suggestion for VS2010, shade types which are IDisposable a different color in the IDE.)
WindowsIdentity.GetCurrent() returns an instance which you should dispose, otherwise you temporarily leak a user handle. (Its a safehandle so its not a huge deal).
Infact, most times you use WindowsIdentity it is good to dispose of the item. Except for one case.
If you call Impersonate() on a WindowsIdentity instance, disposing it will cause hard to diagnose crashes.
It took me a while to work out why, so I thought I would write this up, maybe it’ll save someone else out there the trouble once.
Reflecting through windows identity related code, tokens get duplicated and new WindowsIdentity instances get created all over the place, so it would seem that you were safe to dispose.
However, when you call Impersonate, the WindowsIdentity instance, and its internal safe handle, get stuffed into the current security context, without being copied or duplicated. I don’t know whether that security context disposes the instance later (looks like it doesn’t), but it effectively takes ownership of it, so you can’t.
If you do dispose of it, and you start a timer or queue a work item before the impersonation is undone, when that timer or work item is executed, the .net framework attempts to set up the security context by impersonating again, but the safe handle is already disposed.
As a bonus, you can disable security support in the .Net runtime, in which case the newly corrected code temporarily leaks handles without the runtime being responsible for the leak.