From 7bfc4d37360c28fc27c1412d822b720cfe4c2bb2 Mon Sep 17 00:00:00 2001 From: martincostello Date: Mon, 8 Apr 2024 16:49:47 +0100 Subject: [PATCH] Fix NullReferenceException Fix `NullReferenceException` in `FileSystemWatcher` on Windows if two threads try and dispose the instance at the same time. --- .../src/System/IO/FileSystemWatcher.Win32.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) 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 8508ea648b35f..e1b0be746f26c 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()