tags:

views:

67

answers:

3

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.

+3  A: 

Try making your Application class inheriting CriticalFinalizerObject.

Andrew Bezzub
+1  A: 

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
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).
Unholy
+1  A: 

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