Как правильно обрабатывать список элементов IDisposable в моем Dispose()?C#

Место общения программистов C#
Ответить
Anonymous
 Как правильно обрабатывать список элементов IDisposable в моем Dispose()?

Сообщение Anonymous »


I have a class like this:

public class MyFolderRefresher { public async Task OnRename(RenamedEventArgs e) { // do something } } public class MyDisposableListOfFileSystemWatchers : IDisposable { private List _mWatchers; private MyFolderRefresher _mFolderRefresher; public MyDisposableListOfFileSystemWatchers(List pathsToWatch) { _mFolderRefresher = new MyFolderRefresher(); _mWatchers = new List(); foreach (var path in pathsToWatch) { var fileSystemWatcher = new FileSystemWatcher(path) { NotifyFilter = NotifyFilters.DirectoryName, IncludeSubdirectories = true, InternalBufferSize = 64 * 1024 }; // Listen to events in some different class fileSystemWatcher.Renamed += async (sender, e) => await _mFolderRefresher.OnRename(e); _mWatchers.Add(fileSystemWatcher); } } public void Dispose() { Dispose(true); } private bool _mDisposed = false; protected virtual void Dispose(bool disposing) { if (_mDisposed) { return; } if (disposing) { foreach(var watcher in _mWatchers) { watcher.Dispose(); } _mWatchers.Clear(); } _mDisposed = true; } } The problem is that when calling Dispose() of my MyDisposableListOfFileSystemWatchers class, I sometimes get System.InvalidOperationException. Most of the time it's just a stack trace in the event viewer, but once I caught it in a debugger and was able to see that it was System.InvalidOperationException: Collection was modified; enumeration operation may not execute (not sure if both are the same issue or not).

I'm wondering if I'm doing something wrong in my Dispose(). Specifically:
  • Should I be calling GC.SuppressFinalize(this) in my public void Dispose() ?
  • Is it ok that I Dispose objects that I'm iterating over?
  • Is it ok that I clear the collection, or should I leave that to the Garbage Collector?
  • Since I'm Disposing the Publisher (FileSystemWatcher), am I correct in assuming I don't need to manually unsubscribe from the events?

I've read the documentation but wasn't able to find a definitive answer to those questions and I'm at a bit of a loss when it comes to the System.InvalidOperationException as I don't see how it would be possible that both the constructor and Dispose could be running at the same time (those are the only places where _mWatchers` is modified).


Источник: https://stackoverflow.com/questions/780 ... my-dispose
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»