开发者

Is it safe to wrap Application.Run(new Form()) with a using(...) { } statement?

I am using an external API to interface to a FireWire Camera. The API is propably written in C++ but thankfully it brings its own .NET wrapper DLLs. The API requires the 开发者_运维问答following procedure:

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

Because I need some specific handling code I decided to write a wrapper class for this. I need to keep the ressources open while my Form is open because of Event Handlers, etc. So I thought to make the wrapper easier to use I'd make it a singleton implementing IDisposable so I can wrap it in a using statement. The reason I want a Singleton is to have a controlled and limited way of calling the required API functions:

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;
    }
  }
}

The way I want to use it is this:

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

I'm quite new to C# so I am very unsure of a couple of things:

  1. Will Dispose() always be called in the above using(Singleton.Instance) { ... }? My logging suggests "yes", but I'm unsure...
  2. Is it safe to wrap Application.Run(...) with a using-statement?


The answer to both of your questions is yes:

  • Dispose() will always be called when the using block ends, unless Wrapper.Instance was null when the block began.

  • It is perfectly safe to wrap the call to Run() in a using block.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜