4

Is there a way to release com objects at application crash?

I have the following code:

  public class Application
    : IDisposable
  {
    private bool disposed = false;
    private object realApplication;

    public void Dispose()
    {
      Dispose(true);
    }

    private void Dispose(bool disposing)
    {
      if (!disposed) {
        if (realApplication!=null) {
          Marshal.ReleaseComObject(realApplication);
          realApplication = null;
        }
        disposed = true;
      }
      GC.SuppressFinalize(this);
    }

    ...


    ~Application()
    {
      Dispose(false);
    }
}

But it release com object only at normal application close.

Marat Faskhiev
  • 1,282
  • 6
  • 17
  • 37
  • What sort of crash is it? You're not guaranteed to be able to run this sort of cleanup code in all circumstances. (For instance, consider what happens if the user kills your app through Task Manager.) – Tim Robinson Jul 07 '10 at 07:50
  • Are they in an out-proc server? – sharptooth Jul 07 '10 at 07:51
  • >What sort of crash is it? I'm testing on console application. I just close it by close button (I think it is similar to kill through Task Manager) >Are they in an out-proc server? Yes. >Is this a WinForms app? No. – Marat Faskhiev Jul 07 '10 at 08:01

3 Answers3

3

Try making your Application class inheriting CriticalFinalizerObject.

Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
1

The console close button doesn't have to result in a crash -- take a look at the SetConsoleCtrlHandlerfunction. This lets you install a handler that gets called when the user clicks close, allowing you to clean up.

You can't guarantee the ability to clean up in all circumstances; it's easy to kill your app without giving it a chance to clean up. For instance, your app will never be able to detect the user killing it through Task Manager.

If it's vital that the app cleans up in all circumstances then you might want to look at having a second app, which monitors the first one and cleans up if needed.

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
  • I see. Thanks. I added CriticalFinalizerObject. I hope that it will be enough to cover most cases. If no, I'll try to implement second application (as you say). – Marat Faskhiev Jul 07 '10 at 09:07
1

COM will make the out-proc server cleanup objects itself if the client crashes, but only the objects that are not running any methods. All running methods running on an object need to have completed before that object can be released. There're two reliable solutions: either make all methods run for a very short period of time or craft a separate process for dealing with the COM server.

sharptooth
  • 167,383
  • 100
  • 513
  • 979