namespace ICRebuild.Core; // Called by the framework-thread module manager. One native hook can serve multiple modules. public sealed class SharedModuleResource(Action start) { private ResourceScope? resource; private int owners; private bool cleanupFailed; public void Acquire(ResourceScope owner) { if(cleanupFailed) throw new InvalidOperationException("共享 Hook 清理失败,禁止重复挂接"); if(resource==null) { var created=new ResourceScope(); try { start(created); resource=created; } catch(Exception startup) { try { created.Dispose(); } catch(Exception cleanup) { cleanupFailed=true; throw new AggregateException(startup,cleanup); } throw; } } owners++; try { owner.Defer(Release); } catch { Release(); throw; } } private void Release() { if(--owners!=0) return; var old=resource; resource=null; try { old?.Dispose(); } catch { cleanupFailed=true; throw; } } }