What is the correct way of adding thread-safety to an IDisposable object?

前端 未结 6 2129
别跟我提以往
别跟我提以往 2021-01-31 16:22

Imagine an implementation of the IDisposable interface, that has some public methods.

If an instance of that type is shared between multiple threads and o

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 16:37

    You have to lock every access to the ressource you are going to dispose. I also added the Dispose pattern I normally use.

    public class MyThreadSafeClass : IDisposable
    {
        private readonly object lockObj = new object();
        private MyRessource myRessource = new MyRessource();
    
        public void DoSomething()
        {
            Data data;
            lock (lockObj)
            {
                if (myResource == null) throw new ObjectDisposedException("");
                data = myResource.GetData();
            }
            // Do something with data
        }
    
        public void DoSomethingElse(Data data)
        {
            // Do something with data
            lock (lockObj)
            {
                if (myRessource == null) throw new ObjectDisposedException("");
                myRessource.SetData(data);
            }
        }
    
        ~MyThreadSafeClass()
        {
            Dispose(false);
        }
        public void Dispose() 
        { 
            Dispose(true); 
            GC.SuppressFinalize(this);
        }
        protected void Dispose(bool disposing) 
        {
            if (disposing)
            {
                lock (lockObj)
                {
                    if (myRessource != null)
                    {
                        myRessource.Dispose();
                        myRessource = null;
                    }
                }
                //managed ressources
            }
            // unmanaged ressources
        }
    }
    

提交回复
热议问题