Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forced Garbage collection or reflection to a Private field, which is less evil?

We have a third party library that internally uses a SafeHandle to an unmanaged resource. In some error cases it is necessary to dispose of the object and recreate it. But, there is a bug in the dispose implementation that prevents the Handle from being closed in a subset of these cases. Which prevents new objects from being successfully created until its finalizer runs.

Two solutions (both evil) have been proposed to deal with this until we can get the third party code fixed:

  1. Run a GC.Collect to get the finalizer to run and clean up the object

  2. Use reflection to get at the Handle and close it if dispose fails to do so

which of these is less evil and why? Is there some other method that we haven't considered that is less evil than either of these?

like image 645
Yaur Avatar asked May 21 '11 14:05

Yaur


1 Answers

I'm in favour of private reflection. It's a localized bug, so the solution should be local too. And it's much clearer that what your code intends to do. And you probably can add some tests that notice once the bug has been fixed. So the hack can easily be removed once it's not needed anymore.

...
thirdPartyObject.Dispose();
ThirdPartyDisposeBugWorkaround(thirdPartyObject);
...

void ThirdPartyDisposeBugWorkaround(ThirdPartyClass thirdPartyObject)
{
   //Do private reflection here
}

Forcing a GC on the other hand has a global effect. And there are many reasons(most of them bad) for interfering with the GC. It's much less obvious what your code does. So the call might be kept even once the bug has been fixed.

Old New Thing: Don't use global state to manage a local problem

like image 156
CodesInChaos Avatar answered Sep 27 '22 21:09

CodesInChaos