开发者

Release com objects at application crash

开发者 https://www.devze.com 2023-01-06 18:11 出处:网络
Is there a way to release com objects at application crash? I have the following code: public class Application

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) {
开发者_Go百科          Marshal.ReleaseComObject(realApplication);
          realApplication = null;
        }
        disposed = true;
      }
      GC.SuppressFinalize(this);
    }

    ...


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

But it release com object only at normal application close.


Try making your Application class inheriting CriticalFinalizerObject.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消