diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs index 8508ea648b35f1..e1b0be746f26c8 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs @@ -105,8 +105,12 @@ private void StopRaisingEvents() // increased, such that the disposal operation won't take effect and close the handle // until that P/Invoke returns; if during that time the FSW is restarted, the IsHandleInvalid // check will see a valid handle, unless we also null it out. - _directoryHandle.Dispose(); - _directoryHandle = null; + SafeFileHandle? handle = _directoryHandle; + if (handle is not null) + { + _directoryHandle = null; + handle.Dispose(); + } } private void FinalizeDispose()