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:
- Will
Dispose()
always be called in the aboveusing(Singleton.Instance) { ... }
? My logging suggests "yes", but I'm unsure... - Is it safe to wrap
Application.Run(...)
with ausing
-statement?
The answer to both of your questions is yes:
Dispose()
will always be called when theusing
block ends, unlessWrapper.Instance
wasnull
when the block began.It is perfectly safe to wrap the call to
Run()
in ausing
block.
精彩评论