Managing destructors of managed (C#) and unmanaged (C++) objects

后端 未结 4 974
轻奢々
轻奢々 2021-01-14 02:46

I have a managed object in a c# dll that maintains an anonymous integer handle to an unmanaged object in a c++ dll. Inside the c++ dll, the anonymous integer is used in an s

4条回答
  •  猫巷女王i
    2021-01-14 03:07

    You may be able to solve this quickly by checking Environment.HasShutdownStarted in the finaliser of your C# object (and not calling into the C++ DLL / deleting the C++ object if HasShutdownStarted is true). If you are not in the main AppDomain then you might need to check AppDomain.Current.IsFinalizingForUnload instead (in fact this may be safer in general).

    Note this merely avoids calling the freed library (i.e. avoids running the unmanaged destructor): if the unmanaged library was holding a resource that won't automatically be freed on process shutdown, then that resource could be leaked. (Most OS resources are freed on process shutdown, so this will often not be a concern.) And as Adam notes the CLR finaliser is intended as a failsafe: you really want to free resources more deterministically. Therefore, if structurally possible, Igor's suggestion to implement IDisposable on the C# class and deterministically Dispose the object would be preferable.

提交回复
热议问题