在我编写的软件中,将从外部设备(通过USB连接)中读取一些数据。 我得到了给定的驱动程序(dll文件),它们不是线程安全的,一次只能使用一个实例。 我必须用C#编写一个包装器来封装这些驱动程序。 鉴于我有一个多线程应用程序,我希望确保:
目前,我有一个IDisposable单例,如下所示:
- 始终只使用一个实例(可能是单例模式的包装器?)。
- 可以销毁以释放那里的驱动程序和资源(IDisposable?)。
目前,我有一个IDisposable单例,如下所示:
using System;
using System.Runtime.InteropServices;
namespace Philips.Research.Myotrace.DataReading.Devices
{
class MyDevice: IDisposable
{
private static volatile MyDeviceInstance;
private static object SyncRoot = new Object();
private bool disposed = false;
private MyDevice()
{
//initialize unmanaged resources here (call LoadLibrary, Initialize, Start etc)
}
public MyDevice GetInstance()
{
if (Instance == null)
{
lock (SyncRoot)
{
if (Instance == null)
{
Instance = new MyDevice();
}
}
}
return Instance;
}
public void Dispose()
{
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
//dispose of unmanaged resources here (call Stop and Close from reflection code
Instance = null;
}
this.disposed = true;
}
}
[DllImport("devicedrivers.dll")]
private static extern bool Initialize();
[DllImport("devicedrivers.dll")]
private static extern bool LoadLibrary();
[DllImport("devicedrivers.dll")]
private static extern bool Start();
[DllImport("devicedrivers.dll")]
private static extern bool Stop();
[DllImport("devicedrivers.dll")]
private static extern bool Close();
//and few more
}
}