Skip to content

Microsoft.Extensions.Configuration.Json leaves unobserved task exceptions in background tasks when using reloadOnChange:true #107700

Closed

Description

@genriquez

Description

I've come across an error situations where background tasks are left with unhandled/unobserved task exceptions when using reloadOnChange: true while using filesystem watcher (instead of polling). This happens after the config file and its containing folder are deleted.

We use dispatcher/unhandled/unobserved exception handlers to do bug reporting and terminate the application in a safe manner whenever possible. Currently there is no way to hook into any kind of callback to handle these exceptions and prevent them from bubbling up in background.

Reproduction Steps

I've created a small repro case. You can just run them with dotnet run MSConfigCrashTests.csproj and some basic console logging while happen showing the state of the config loaded, and what handlers were triggered:

repro-delete-fswatcher.zip

Expected behavior

Background exceptions should not be left to bubble up as UnobservedTaskExceptions. If not by default, at least there should be a way to hook a handler and prevent the exception from bubbling up, like load exceptions can be handled (see attached project):

update-fswatcher.zip

Actual behavior

Background exceptions trigger the TaskScheduler.UnobservedTaskException handler with no other way of handling them. The exception is as follows:

System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. (One or more errors occurred. (Error reading the C:\Users\XXX\AppData\Local\Temp\testdir\ directory.))
 ---> System.AggregateException: One or more errors occurred. (Error reading the C:\Users\XXX\AppData\Local\Temp\testdir\ directory.)
 ---> System.IO.FileNotFoundException: Error reading the C:\Users\XXX\AppData\Local\Temp\testdir\ directory.
   at System.IO.FileSystemWatcher.StartRaisingEvents()
   at Microsoft.Extensions.FileProviders.Physical.PhysicalFilesWatcher.TryEnableFileSystemWatcher()
   at Microsoft.Extensions.FileProviders.Physical.PhysicalFilesWatcher.CreateFileChangeToken(String filter)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider.Watch(String filter)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.<.ctor>b__1_0()
   at Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration`1.OnChangeTokenFired()
   at Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration`1.<>c.<RegisterChangeTokenCallback>b__7_0(Object s)
   at System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source)
   at System.Threading.CancellationTokenSource.Register(Delegate callback, Object stateForCallback, SynchronizationContext syncContext, ExecutionContext executionContext)
   at System.Threading.CancellationToken.Register(Delegate callback, Object state, Boolean useSynchronizationContext, Boolean useExecutionContext)
   at System.Threading.CancellationToken.UnsafeRegister(Action`1 callback, Object state)
   at Microsoft.Extensions.Internal.ChangeCallbackRegistrar.UnsafeRegisterChangeCallback[T](Action`1 callback, Object state, CancellationToken token, Action`1 onFailure, T onFailureState)
   at Microsoft.Extensions.Primitives.CancellationChangeToken.RegisterChangeCallback(Action`1 callback, Object state)
   at Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration`1.RegisterChangeTokenCallback(IChangeToken token)
   at Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration`1.OnChangeTokenFired()
   at Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration`1.<>c.<RegisterChangeTokenCallback>b__7_0(Object s)
   at System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source)
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   --- End of inner exception stack trace ---
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   at Microsoft.Extensions.FileProviders.Physical.PhysicalFilesWatcher.<>c.<.cctor>b__43_0(Object state)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
   --- End of inner exception stack trace ---

Regression?

No response

Known Workarounds

Two options:

  • Using polling with active polling seems to bypass this.
  • Wrapping the FileProvider so Watch(string) returns a wrapped IChangeToken that wraps actions passed to RegisterChangeCallback(Action<object?>,object?) to add a try/catch.

Configuration

$ dotnet --version
8.0.200

Repro project is net6. Still repros if changed to net8.

Other information

No response

Activity

  1. ghost added
    needs-area-label
    on Sep 11, 2024
  2. added
    untriaged
    on Sep 11, 2024
  3. added and removed
    needs-area-label
    on Sep 11, 2024
  4. dotnet-policy-service commented on Sep 11, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-extensions-configuration
    See info in area-owners.md if you want to be subscribed.

  5. dotnet-policy-service commented on Sep 11, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-extensions-filesystem
    See info in area-owners.md if you want to be subscribed.

  6. added this to the Future milestone on Sep 17, 2024
  7. added
    needs-further-triage
    and removed
    untriaged
    on Sep 17, 2024
  8. added
    help wanted
    and removed
    needs-further-triage
    on Feb 9, 2025
  9. jeffhandley commented on Feb 9, 2025

    @jeffhandley
    Member

    Thank you for the detailed report and repro, @genriquez. I've marked this as help wanted [up-for-grabs] Good issue for external contributors as I do not expect our team to be able to get to this during .NET 10.

  10. cincuranet commented on Mar 12, 2026

    @cincuranet
    Contributor

    Triage: We will investigate.

  11. mrek-msft commented on Apr 1, 2026

    @mrek-msft
    Member

    I investigated what's going on. I think root cause is that PhysicalFilesWatcher.TryEnableFileSystemWatcher can throw despite Try in name. It can throw because EnableRaisingEvents setter can throw. Something like minimal repro to trigger the same exception with minimal wrappers overhead:

    using Microsoft.Extensions.FileProviders.Physical;
    
    var dir = @"C:\Work\Delete\pfwrepro";
    
    // dir exists at FSW and PFW ctor time
    Directory.CreateDirectory(dir);
    
    using var fsw = new FileSystemWatcher(dir);
    using var pfw = new PhysicalFilesWatcher(dir, fsw, false);
    
    // dir deletes in meantime
    Directory.Delete(dir);
    
    // throws FileNotFoundException, not because test.txt do not exists, but because FSW monitored folder no longer exists.
    // We do not enable FSW before first ChangeToken is created. As far, FSW was created but not running.
    var ct = pfw.CreateFileChangeToken("test.txt");

    Public pfw.CreateFileChangeToken() contract says that it throws only ArgumentNullException and no more exceptions are mentioned. @tarekgh, @ericstj or recent MEFS consultants @jozkee, @adamsitnik can you confirm that intended behavior of PFW was to shield user from IO and other exceptions and work on best effort basis in these cases? Should we degrade to polling behavior in such cases? Or should clients wrap calls to CreateFileChangeToken in try catch and implement fallback themselves?

  12. svick commented on Apr 1, 2026

    @svick
    Member

    @mrek-msft My PR #126411 should handle this situation gracefully. After it's merged PhysicalFilesWatcher will no longer throw an exception here. I am going to add a test for this exact case.

  13. added a commit that references this issue on Apr 1, 2026
  14. assigned and unassigned on Apr 1, 2026
  15. modified the milestones: Future, 11.0.0 on Apr 1, 2026
  16. removed
    help wanted
    on Apr 2, 2026
  17. added a commit that references this issue on Apr 9, 2026
    b9ef488
  18. locked and limited conversation to collaborators on May 10, 2026
  19. added a commit that references this issue on Jul 15, 2026
    921edc7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions