Skip to content

fix: resolve COM memory instability and ensure graceful Excel teardown#1

Draft
eli-lindner-sj wants to merge 5 commits into
mitchell-tesch:mainfrom
eli-lindner-sj:fix/com-memory-stability
Draft

fix: resolve COM memory instability and ensure graceful Excel teardown#1
eli-lindner-sj wants to merge 5 commits into
mitchell-tesch:mainfrom
eli-lindner-sj:fix/com-memory-stability

Conversation

@eli-lindner-sj
Copy link
Copy Markdown

@eli-lindner-sj eli-lindner-sj commented Jun 1, 2026

This PR implements a scope-isolated cleanup pattern to ensure reliable Excel lifecycle management:

Key Changes:

  • Scope Isolation: Refactored ExcelWorker.Run() to move core processing into a nested ExecuteRunLoop. This ensures that all local COM references naturally go out of scope and become eligible for collection before the "double-tap" GC collection (GC.Collect() + GC.WaitForPendingFinalizers()) is triggered in the finally block.
  • Removed Manual Release: Eliminated all calls to Marshal.FinalReleaseComObject in favor of the more stable scope-isolated GC pattern, preventing DLR-related interop exceptions.
  • Process Abstraction: Introduced IProcessInterop to abstract OS-level process interactions. This allowed for the replacement of "hollow" tests with deterministic unit tests that verify tracking and fallback-kill logic without requiring a real Excel instance.
  • Resilient PID Tracking: Improved GetExcelProcessId to handle failures gracefully, ensuring that valid PIDs are always tracked for cleanup even if initial resolution is delayed.

Removed manual FinalReleaseComObject calls on dynamic COM objects to prevent InvalidComObjectException. Implemented a double-tap GC collection pattern in ExcelProcessTracker to ensure reliable RCW release and graceful Excel shutdown.
Fixed a 64-bit HWND casting bug in ExcelProcessTracker and optimized COM lifecycle management by clearing local dynamic references before triggering the GC double-tap to ensure RCWs are not rooted during collection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant