diff --git a/src/FS.Physical/PhysicalFilesWatcher.cs b/src/FS.Physical/PhysicalFilesWatcher.cs index 36e8fc8d..0452453a 100644 --- a/src/FS.Physical/PhysicalFilesWatcher.cs +++ b/src/FS.Physical/PhysicalFilesWatcher.cs @@ -373,8 +373,27 @@ private void TryEnableFileSystemWatcher() if ((!_filePathTokenLookup.IsEmpty || !_wildcardTokenLookup.IsEmpty) && !_fileWatcher.EnableRaisingEvents) { - // Perf: Turn off the file monitoring if no files to monitor. - _fileWatcher.EnableRaisingEvents = true; + // Don't capture the current ExecutionContext and its AsyncLocals onto the events causing them to live forever + var restoreFlow = false; + try + { + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + // Perf: Turn off the file monitoring if no files to monitor. + _fileWatcher.EnableRaisingEvents = true; + } + finally + { + // Restore the current ExecutionContext + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } } } } diff --git a/test/FS.Physical.Tests/PhysicalFileProviderTests.cs b/test/FS.Physical.Tests/PhysicalFileProviderTests.cs index bf36aec8..71c7edd9 100644 --- a/test/FS.Physical.Tests/PhysicalFileProviderTests.cs +++ b/test/FS.Physical.Tests/PhysicalFileProviderTests.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing.xunit;