diff --git a/src/Microsoft.AspNet.Server.Kestrel/Networking/UvLoopHandle.cs b/src/Microsoft.AspNet.Server.Kestrel/Networking/UvLoopHandle.cs index c6ad9c7f6c..f0f3d454b1 100644 --- a/src/Microsoft.AspNet.Server.Kestrel/Networking/UvLoopHandle.cs +++ b/src/Microsoft.AspNet.Server.Kestrel/Networking/UvLoopHandle.cs @@ -28,17 +28,20 @@ namespace Microsoft.AspNet.Server.Kestrel.Networking _uv.stop(this); } - protected override bool ReleaseHandle() + unsafe protected override bool ReleaseHandle() { var memory = this.handle; if (memory != IntPtr.Zero) { + // loop_close clears the gcHandlePtr + var gcHandlePtr = *(IntPtr*)memory; + _uv.loop_close(this); handle = IntPtr.Zero; - DestroyMemory(memory); + + DestroyMemory(memory, gcHandlePtr); } return true; } - } } diff --git a/src/Microsoft.AspNet.Server.Kestrel/Networking/UvMemory.cs b/src/Microsoft.AspNet.Server.Kestrel/Networking/UvMemory.cs index d1f07627bf..37e75ef537 100644 --- a/src/Microsoft.AspNet.Server.Kestrel/Networking/UvMemory.cs +++ b/src/Microsoft.AspNet.Server.Kestrel/Networking/UvMemory.cs @@ -54,6 +54,11 @@ namespace Microsoft.AspNet.Server.Kestrel.Networking unsafe protected static void DestroyMemory(IntPtr memory) { var gcHandlePtr = *(IntPtr*)memory; + DestroyMemory(memory, gcHandlePtr); + } + + unsafe protected static void DestroyMemory(IntPtr memory, IntPtr gcHandlePtr) + { if (gcHandlePtr != IntPtr.Zero) { var gcHandle = GCHandle.FromIntPtr(gcHandlePtr);