0

I am creating a wrapper for a COM library that interacts with IBM mainframes. It can only be accessed from a single thread. To get around this, I've created a System.Windows.Threading.Dispatcher to handle running all interactions on a dedicated thread.

My problem is that if the object is not disposed explicitly, the dispatcher stays running after a WinForm application exits. The finalize method is never called for the object that creates the dispatcher. I need the sessions to be closed reliably to prevent unnecessary connections.

If I call GC.Collect on application exit, it will close fine. However, the library that I created will be used by mostly inexperienced developers. I cannot count on them always Disposing, collecting garbage or all committing to either WinForms or WPF to hook into application exit events.

I've read that if a class has a finalizer, its cleanup gets deferred until later. That may be part of the issue, but I can get around having a finalizer?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Josh Brown
  • 935
  • 1
  • 11
  • 21

2 Answers2

1

The finalize method is never called for the object that creates the dispatcher

The finalizer is called, when GC decides to perform grabage collection. You shouldn't rely on finalizer, when you need to dispose resources explicitly, because you shouldn't interfere in GC work.

I cannot count on them always Disposing

I'm afraid, you have no choice. Implement IDisposable and force your users to call Dispose. This is normal practice in .NET.

Dennis
  • 37,026
  • 10
  • 82
  • 150
1

Using WPF's dispatcher in a Winforms app isn't exactly a great idea. Check this answer for the equivalent Winforms approach.

Getting the COM objects released otherwise doesn't take a great effort. Just set the thread's IsBackground property to true. Which will make the CLR automatically abort the thread when the program's main thread exits. The CLR then runs one final garbage collection, the exact equivalent of you calling GC.Collect() explicitly.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536