Skip to content

Commit 17e42d8

Browse files
authored
Make the C# object disposable (#179)
* Make C# object with native handle disposable The wrapper user can decide to release the native handle immediately to avoid potential resource race issues. * Implement dispose pattern following the Microsoft documentation https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose * Refine the change according to pull request comments Co-authored-by: Kevin Zhang <Ping.Zhang@autodesk.com>
1 parent 09cbb2a commit 17e42d8

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

Source/buildbindingcsharp.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -977,7 +977,9 @@ func buildBindingCSharpImplementation(component ComponentDefinition, w LanguageW
977977
class := component.Classes[i]
978978

979979
CSharpParentClassName := ""
980-
if !component.isBaseClass(class) {
980+
if component.isBaseClass(class) {
981+
CSharpParentClassName = ": IDisposable"
982+
} else {
981983
if class.ParentClass == "" {
982984
CSharpParentClassName = ": " + CSharpBaseClassName
983985
} else {
@@ -996,14 +998,28 @@ func buildBindingCSharpImplementation(component ComponentDefinition, w LanguageW
996998
w.Writeln(" Handle = NewHandle;")
997999
w.Writeln(" }")
9981000
w.Writeln("")
999-
w.Writeln(" ~C%s ()", class.ClassName)
1001+
w.Writeln(" protected virtual void Dispose(bool disposing)")
10001002
w.Writeln(" {")
1003+
w.Writeln(" if (disposing)")
1004+
w.Writeln(" {")
1005+
w.Writeln(" // dispose managed state (managed objects).")
1006+
w.Writeln(" }")
10011007
w.Writeln(" if (Handle != IntPtr.Zero) {")
10021008
w.Writeln(" Internal.%sWrapper.%s (Handle);", NameSpace, component.Global.ReleaseMethod)
10031009
w.Writeln(" Handle = IntPtr.Zero;")
10041010
w.Writeln(" }")
10051011
w.Writeln(" }")
10061012
w.Writeln("")
1013+
w.Writeln(" public void Dispose()")
1014+
w.Writeln(" {")
1015+
w.Writeln(" // Dispose of unmanaged resources.")
1016+
w.Writeln(" Dispose(true);")
1017+
w.Writeln(" // Suppress finalization.")
1018+
w.Writeln(" GC.SuppressFinalize(this);")
1019+
w.Writeln(" }")
1020+
w.Writeln("")
1021+
w.Writeln(" ~C%s () => Dispose(false);", class.ClassName)
1022+
w.Writeln("")
10071023

10081024
w.Writeln(" protected void CheckError (Int32 errorCode)")
10091025
w.Writeln(" {")

0 commit comments

Comments
 (0)