C# Finalizer for .Net Framework class System.Security.Principal.WindowsIdentity

Ok, first I'll not bark at the obvious poor choice made to not support a 'delete' statement to force finalizing an object; rather I'll assume your approach is correct...

According to everything I've read, If you allocate unmanaged resources within an object one should support the System.IDisposable interface and free resources there.

This post is to point out that in the Framework 1.1 the class System.Security.Principal.WindowsIdentity allocates a global windows handle when instantiated with a security token.  This handle is not released until the destructor is called.  This is contrary to your own best practice, is it not

Background: I'm implementing a secured remoting channel built on top of RPC.  Since I need to create a WindowsIdentity and place this in the property System.Threading.Thread.CurrentPrincipal on each remote call I consume a windows handle on each call.  This works until the 32k worth of global handles is consumed waiting on the finalizers of your WindowsIdentity class.

Trying to force colleciton, I tried calling GC.Collect() and GC.GetTotalMemory(true).  This seemed to solve the problem at the expense of about an order of magnatude in performance.

Giving up on GC to do the work for me, I'm forced to the solution below.  This snipit mannually calls the destructor of the object after unregistering the instance from the pending finalizers.  Error handling has been removed for simplification so this is abbreviated but roughly accurate:

GC.SuppressFinalize( obj );
MemberInfo[] members = obj.GetType().GetMember( "Finalize", MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance );
((MethodInfo)members[0]).Invoke( obj, BindingFlags.NonPublic | BindingFlags.Instance, null, null, Thread.CurrentThread.CurrentCulture );

Frankly I'm really supprized I'm allowed to execute the code above, but it does work.  This is really ugly, but what are my alternatives

Outside of writing my own WindowsIdentity (which I do not consider an alternative) what are my options




Answer this question

C# Finalizer for .Net Framework class System.Security.Principal.WindowsIdentity

  • Beaver01

    Do you think the workaround posted will break in v1.1

  • tao84

    You're right, WindowsIdentity should follow the Disposable pattern.  That was a bug in the v1.1 framework which has been fixed in v2.0.

    -Shawn

  • blackwing

    I've had a look at WindowsIdentity and I agree, there seems to be serious problem there. It should implement IDisposable.

    I suggest you post a suggestion on the Microsoft Product Feedback Center.

    For now, there is not a lot you can do, without writing your own IIdentity and IPrinciple. Comment it with a // HACK and wait for Microsoft's response.

  • C# Finalizer for .Net Framework class System.Security.Principal.WindowsIdentity