Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用using(…){}语句包装Application.Run(newform())是否安全?_C#_C# 3.0_Singleton_Using Statement - Fatal编程技术网

C# 使用using(…){}语句包装Application.Run(newform())是否安全?

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的打开状态。因此,为

我正在使用一个外部API来连接FireWire摄像头。API是用C++编写的,但值得庆幸的是它带来了自己的.NET包装器DLL。API需要以下程序:

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()
    的调用封装在
    中是非常安全的


    感谢您回答我的问题!