Disposing of FileSystemWatcher

后端 未结 2 1829
南方客
南方客 2020-12-17 02:46

So my understanding is that whenever using a class that implements IDisposable, it\'s parent also needs to implement IDisposable interface. (FileWatcher using FileSystemWatc

相关标签:
2条回答
  • 2020-12-17 03:19

    When shutting down an application, run the dispose method.

    According to the method requested, when you want to dispose of something when your shutting down the program.

    if you are using a class via, then IDisposable is for disposing the class object, but essentially you still might want to do it when you are shutting down the program

    bool myFlag = false;
    private FileSystemWatcher watcher;
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
     {
               myFlag = true;
               if(myFlag)
               watcher.Dispose(); //Your FileSystemWatcher object
     }
    
    0 讨论(0)
  • 2020-12-17 03:19

    Yes, implementing IDisposable is the right solution in this case (in my opinion). Your object is long-lived and has to live outside the scope of any particular function call so all function-scope level solutions (using, try..finally, etc.) are out.

    For this, IDisposable is a standard pattern in .NET and you can easily dispose of the nested object when FileWatcher is disposed of.

    0 讨论(0)
提交回复
热议问题