Is there any benefit to implementing IDisposable on classes which do not have resources?

后端 未结 11 2089
挽巷
挽巷 2020-12-14 05:14

In C#, if a class, such as a manager class, does not have resources, is there any benefit to having it : IDisposable?

Simple example:

pu         


        
11条回答
  •  死守一世寂寞
    2020-12-14 06:14

    IDisposable is also great if you want to benefit the using () {} syntax.

    In a WPF project with ViewModels, I wanted to be able to temporarily disable NotifyPropertyChange events from raising. To be sure other developers will re-enable notifications, I wrote a bit of code to be able to write something like:

    using (this.PreventNotifyPropertyChanges()) {
        // in this block NotifyPropertyChanged won't be called when changing a property value
    }
    

    The syntax looks okay and is easily readable. For it to work, there's a bit of code to write. You will need a simple Disposable object and counter.

    public class MyViewModel {
        private volatile int notifyPropertylocks = 0; // number of locks
    
        protected void NotifyPropertyChanged(string propertyName) {
            if (this.notifyPropertylocks == 0) { // check the counter
                this.NotifyPropertyChanged(...);
            }
        }
    
        protected IDisposable PreventNotifyPropertyChanges() {
            return new PropertyChangeLock(this);
        }
    
        public class PropertyChangeLock : IDisposable {
            MyViewModel vm;
    
            // creating this object will increment the lock counter
            public PropertyChangeLock(MyViewModel vm) {
                this.vm = vm;
                this.vm.notifyPropertylocks += 1;
            }
    
            // disposing this object will decrement the lock counter
            public void Dispose() {
                if (this.vm != null) {
                    this.vm.notifyPropertylocks -= 1;
                    this.vm = null;
                }
            }
        }
    }
    

    There are no resources to dispose here. I wanted a clean code with a kind of try/finally syntax. The using keyword looks better.

提交回复
热议问题