包装应用程序是否安全?用using(..){}语句运行(new Form())

本文关键字:语句 运行 new Form 应用程序 安全 using 包装 是否 | 更新日期: 2023-09-27 18:02:44

我使用外部API接口到火线相机。API可能是用c++编写的,但幸运的是它带来了自己的。net包装器dll。该API需要以下过程:

ApiResource.Init();
// ... use the ressource here ...
ApiResource.CloseAll();
ApiResource.Release();

因为我需要一些特定的处理代码,我决定为此编写一个包装器类。我需要保持资源打开,而我的表单是开放的,因为事件处理程序等。所以我想让包装器更容易使用,我让它成为一个实现IDisposable的单例,这样我就可以把它包装在using语句中。我想要Singleton的原因是有一种控制和有限的方式来调用所需的API函数:

class Wrapper : IDisposable {
  private Wrapper _instance;
  public Wrapper Instance
  {
    get
    {
      if(_instance == null)
        _instance = new Wrapper();
      return _instance;
    }
  }
  private Wrapper ()
  {
    ApiResource.Init();
    _disposed = false;
  }
  // Finalizer is here just in case someone
  // forgets to call Dispose()
  ~Wrapper() {
    Dispose(false);
  }
  private bool _disposed;
  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }
  protected virtual void Dispose(bool disposing)
  {
    if(!_disposed)
    {
       if(disposing)
       {
       }
       ApiResource.CloseAll();
       ApiResource.Release();
       _instance = null;
       log("Wrapper disposed.");
       _disposed = true;
    }
  }
}

我想这样使用它:

using(Wrapper.Instance) {
  Application.Run(new Form());
}

我对c#很陌生,所以我对一些事情很不确定:

  1. Dispose()是否总是在上述using(Singleton.Instance) { ... }中调用?我的日志提示"是",但我不确定…
  2. using -语句包装Application.Run(...)是否安全?

包装应用程序是否安全?用using(..){}语句运行(new Form())

你的两个问题的答案都是:

  • Dispose()总是在using块结束时被调用,除非Wrapper.Instance在块开始时是null

  • Run()调用包装在using块中是完全安全的。