File GDB shared-resource lifetime and finalizer crash

Hi ThinkGeo team,

Separate FileGeoDatabaseFeatureSource instances pointing to the same database can
interfere with each other’s native resource lifetime. We observed process termination
with this finalizer exception:

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Geodatabase'.
   at Esri.FileGDB.Table.Shutdown()
   at Esri.FileGDB.Table.Dispose(Boolean A_0)
   at Esri.FileGDB.Table.Finalize()
   at System.GC.RunFinalizers()

Inspected versions: ThinkGeo.FileGeoDatabase 15.0.0-beta233 and
Esri.FileGDBAPI.dll from ThinkGeo.Dependency.FileGeoDatabase 14.5.4.
The findings below come from assembly inspection.

Lifetime and synchronization findings:

  • FileGeoDatabaseFeatureSource delegates to ThinkGeoObfuscated.j.jt, which has
    process-wide geodatabase and table caches. Separate sources for the same path/table
    reuse the same native objects. Closing a source removes and disposes its cached
    table and, when the table dictionary becomes empty, the geodatabase. There is no
    source-owner reference count in this path.
  • The table-cache lookup checks for an existing entry before taking the shared lock;
    the subsequent locked OpenTable/assignment does not recheck it. Concurrent opens
    can overwrite a cached table without disposing the previous object.
  • GetFirstFeaturesWellKnownTypeCore opens an additional, uncached table and searches
    its first row. This operation does not hold the shared lock across opening, reading
    and cleanup. Another source can close the cached geodatabase during that operation.
  • The cleanup helper catches exceptions from both Table.Close() and Dispose().
    In the Esri wrapper, Table.Shutdown() accesses Geodatabase.NativeGeodatabase,
    whose getter throws when the database is disposed. If this makes Table.Dispose()
    fail, it never reaches GC.SuppressFinalize; the later finalizer can throw again.
    Also, Geodatabase.OpenTable() allocates a table before the native open and does
    not dispose that table on an open failure.

Lock contention: full-feature reads hold the shared lock for the entire scan.
A background GetAllFeatures() on one source can therefore block a metadata open
on another source. Separate layer instances do not isolate these operations.

Suggested SDK reproduction cases (not yet run):

  1. Repeatedly open/read/close separate FileGeoDatabaseFeatureLayer instances for
    the same path/table on concurrent workers. Include QueryTools.GetColumns(),
    QueryTools.GetFirstFeaturesWellKnownType() and
    FeatureSource.GetAllFeatures(ReturningColumnsType.NoColumns). Force collection
    and wait for pending finalizers after each completed batch in the test process
    to expose orphaned tables sooner.
  2. Overlap a geometry-type probe on one source with closing another source for the
    same database. Verify that the probe’s uncached table remains valid through cleanup.
  3. Exercise a failing table open followed by database cleanup and GC; verify that
    a partially opened table cannot later terminate the process.

Could you investigate cache ownership/synchronization and the Esri wrapper’s failed
open/disposal paths? Closing one source should not invalidate another source’s active
native objects, and finalization should not throw after database cleanup. Please
also clarify the supported concurrency contract for separate File GDB sources and
whether full reads must serialize metadata access across sources.

Thanks!

Hi Julian,

All of it checks out, and all three of your cases fail on the current build the way you predicted: the finalizer crash with exactly your stack, an access violation inside the row enumerator, and concurrent workers dying or sticking inside the native CloseGeodatabase call.

The cause is what you found: the process-wide geodatabase and table cache had no owner count, so one source’s Close disposed native objects other sources were still using, and several paths (the geometry-type probe, Open, GetBoundingBox, GetColumns) ran native calls outside the lock. Esri’s Table.Dispose then throws before GC.SuppressFinalize, and the finalizer throws again.

They have been fixed in ThinkGeo.FileGeoDatabase 15.0.0-beta238:

  • The shared geodatabase and table are reference-counted. Each source takes a hold on Open and releases it on Close; the last one closes the table, then the geodatabase. Closing one source never touches another’s objects.
  • Every native call goes through the one process-wide lock, including the geometry-type probe, which now reads the table the source already holds.
  • The table name is checked against the catalog before OpenTable, so a wrong name throws an ArgumentException and never reaches Esri’s leaking failure path. If an open or create fails anyway, that geodatabase is kept alive for the process so the leaked Table’s finalizer has nothing to throw about.
  • If Table.Dispose still throws during cleanup, we call GC.SuppressFinalize ourselves.

Concurrency contract: separate FileGeoDatabaseFeatureSource instances (and the clones the SDK makes for tile workers) may be used from separate threads. All native work on any File GDB serialises on one lock because the Esri API is single-threaded, so a full GetAllFeatures scan holds the lock for its duration and a metadata call on another source waits for it. For large tables prefer the bounded reads over GetAllFeatures on a background worker.

Your three cases now run clean for minutes with 8 workers and a forced GC every 250 ms.

Thanks,
Ben

Hi Ben, great to have you back :smiley:

Thanks for this fix. We hit a performance issue with the changes, however:

Could you optimize table-name validation in ThinkGeo.FileGeoDatabase? On beta239,
discovering 91 classes in a File GDB containing feature datasets took 82.9 seconds:

Phase Total
Initial catalog enumeration 1.100 s
Opening the 91 classes 81.222 s
First-feature geometry-type probes 0.560 s
Close/cleanup 0.023 s

All 91 classes opened successfully. We kept the first opened source alive throughout
discovery, so the database stayed open between probes. Individual class opens still
cost about 0.9 seconds. Subsequent selection/preview logs also show 0.88–1.11 seconds
in Open, while a 2,000-feature geometry read took 37–60 ms.

Inspecting beta239 shows that each uncached native table open validates the name by
re-enumerating the entire catalog before OpenTable. This enumerates feature datasets,
then feature classes and tables under each dataset and at the root. Keeping a source
open reuses the geodatabase but does not reuse that catalog. The application timings
measure Open as a whole; we have not profiled validation separately from native table
opening and column loading.

Could you avoid repeating the full catalog enumeration for every table, for example
by reusing a catalog snapshot within the shared geodatabase owner, with appropriate
invalidation for schema/external changes? Please retain invalid-name validation,
reference counting, locking, and the finalizer protections from beta238.

Minimal reproduction on a GDB with many classes in feature datasets (add the normal
ThinkGeo licensing setup). No full feature scans or rendering are needed:

var names = FileGeoDatabaseFeatureSource.GetTableNames(path);
if (names.Count == 0) return;

var holder = new FileGeoDatabaseFeatureSource(path, names[0], string.Empty);
try
{
    holder.Open();
    foreach (string name in names)
    {
        var source = new FileGeoDatabaseFeatureSource(path, name, string.Empty);
        try
        {
            var timer = System.Diagnostics.Stopwatch.StartNew();
            source.Open();
            timer.Stop();
            Console.WriteLine($"Open {name}: {timer.Elapsed.TotalMilliseconds:F1} ms");
            _ = source.GetFirstFeaturesWellKnownType();
        }
        finally { source.Close(); }
    }
}
finally { holder.Close(); }

Our synthetic fixture with 68 classes at the root showed 10.5 seconds median with
an owner held open; that did not represent the much higher cost of this GDB. Please
include classes inside feature datasets when checking the optimization.

Hi Julian,

Yep, it’s good to be back :slight_smile:

Thanks for the measurements. They match what we see: on a synthetic geodatabase with 91 classes in ten feature datasets your loop took 19 s on beta239, about 210 ms per Open, and one GetTableNames call took the same 210 ms, so every open was paying for one full walk of the catalog. Your geodatabase is heavier per item, hence 0.9 s.

Fixed in ThinkGeo.FileGeoDatabase 15.0.0-beta240:

  • The catalog is enumerated once per open geodatabase and kept with the shared geodatabase owner. While any source holds the geodatabase, the name check of every further open is a lookup in that snapshot.
  • A name the snapshot does not have triggers one fresh enumeration before it is refused, so a table added since, by you or by another process, still opens, and only a wrong name pays for a scan.
  • If Esri’s OpenTable fails for a name the snapshot had (the table was removed while the geodatabase was open), the snapshot is dropped and rebuilt on the next check, and the beta238 protections cover that open.
  • GetTableNames always enumerates afresh and refreshes the snapshot, so your discovery sequence walks the catalog twice in total: once for the listing and once for the first open, since the listing releases the geodatabase before the holder opens it again.
  • Reference counting, the one lock, invalid-name validation and the finalizer protections are as in beta238.

Your loop with the holder on the synthetic 91-class geodatabase: 0.07 s for the 91 opens (median 0.7 ms, max 1.2 ms) against 19 s on beta239. The three cases from your first post still run clean on this build.

One thing to keep in mind: the snapshot lives with the open geodatabase. An Open while no other source or layer is open on that geodatabase still enumerates the catalog once, so for the later selection and preview opens keep a source, or the layer you are showing, open on that geodatabase, as you do during discovery.

Thanks,
Ben