From c648fc7b84dea32e66f87b760832b7f7a79dd63c Mon Sep 17 00:00:00 2001 From: Joel Dice Date: Thu, 29 Aug 2024 12:44:46 -0600 Subject: [PATCH] C#: do not drop resource handles in finalizers (#1040) * C#: do not drop resource handles in finalizers As of this writing, we cannot safely drop a handle to an imported resource from a .NET finalizer because it may still have one or more open child resources. Once WIT has explicit syntax for indicating parent/child relationships, we should be able to use that information to keep track of child resources automatically in generated code, at which point we'll be able to drop them in the correct order from finalizers. Fixes #1039 Signed-off-by: Joel Dice * remove finalizers per PR feedback Signed-off-by: Joel Dice --------- Signed-off-by: Joel Dice --- crates/csharp/src/lib.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/csharp/src/lib.rs b/crates/csharp/src/lib.rs index 7b9253ed7..e4d574d3b 100644 --- a/crates/csharp/src/lib.rs +++ b/crates/csharp/src/lib.rs @@ -1444,6 +1444,11 @@ impl InterfaceGenerator<'_> { .map(|key| self.resolve.name_world_key(key)) .unwrap_or_else(|| "$root".into()); + // As of this writing, we cannot safely drop a handle to an imported resource from a .NET finalizer + // because it may still have one or more open child resources. Once WIT has explicit syntax for + // indicating parent/child relationships, we should be able to use that information to keep track + // of child resources automatically in generated code, at which point we'll be able to drop them in + // the correct order from finalizers. uwriteln!( self.src, r#" @@ -1458,22 +1463,17 @@ impl InterfaceGenerator<'_> { public void Dispose() {{ Dispose(true); - GC.SuppressFinalize(this); }} [DllImport("{module_name}", EntryPoint = "[resource-drop]{name}"), WasmImportLinkage] private static extern void wasmImportResourceDrop(int p0); protected virtual void Dispose(bool disposing) {{ - if (Handle != 0) {{ + if (disposing && Handle != 0) {{ wasmImportResourceDrop(Handle); Handle = 0; }} }} - - ~{upper_camel}() {{ - Dispose(false); - }} "# ); }