In the software I am writing I will read some data from an external device (connected via USB). The drivers I have been given (dll file) are not thread safe and only one instance can be used at a time. I have to write a wrapper to these drivers in C#. Given that I have a multi-threaded application, I would like to make sure that:
- Always only one instance is used (probably the wrapper being a singleton?).
- It can be disposed of to release the drivers and resources there (IDisposable?).
From Disposable Singleton I can see that the opinions are divided, can a singleton be IDisposable or not. Maybe there is a better solution to both? Any help welcome.
For now I have an IDisposable singleton, like below:
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
    }
}
 
     
     
    