C# 使用using(…){}语句包装Application.Run(newform())是否安全?
我正在使用一个外部API来连接FireWire摄像头。API是用C++编写的,但值得庆幸的是它带来了自己的.NET包装器DLL。API需要以下程序:C# 使用using(…){}语句包装Application.Run(newform())是否安全?,c#,c#-3.0,singleton,using-statement,C#,C# 3.0,Singleton,Using Statement,我正在使用一个外部API来连接FireWire摄像头。API是用C++编写的,但值得庆幸的是它带来了自己的.NET包装器DLL。API需要以下程序: ApiResource.Init(); // ... use the ressource here ... ApiResource.CloseAll(); ApiResource.Release(); 因为我需要一些特定的处理代码,所以我决定为此编写一个包装器类。由于事件处理程序等原因,我需要在窗体打开时保持Resources的打开状态。因此,为
ApiResource.Init();
// ... use the ressource here ...
ApiResource.CloseAll();
ApiResource.Release();
因为我需要一些特定的处理代码,所以我决定为此编写一个包装器类。由于事件处理程序等原因,我需要在窗体打开时保持Resources的打开状态。因此,为了使包装器更易于使用,我将其设置为一个实现IDisposable
的单例,以便使用语句将其包装在中。我想要单例的原因是要有一种可控且有限的方式来调用所需的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#相当陌生,因此我对以下几点非常不确定:
在上述中是否总是使用(Singleton.Instance){…}
调用Dispose()
?我的日志显示“是”,但我不确定
包装应用程序是否安全。使用语句运行(…)
两个问题的答案都是肯定的:
Dispose()
将始终在using
块结束时调用,除非Wrapper.Instance
在块开始时为null
- 使用
块将对Run()
的调用封装在中是非常安全的
感谢您回答我的问题!