Skip to content

CascadingValueSource crashes because subscriber are added asynchronously #56741

@inf9144

Description

@inf9144

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

In cascading value source in the function NotifyChangedAsync() the subscribers are enumerated using a foreach loop. The loop starts an asynchronous task for every subscriber to notify it. If you now have a subscriber like an AuthorizeView (for CascadingAuthenticationState which was added via services.AddCascadingAuthenticationState()) which hosts controls that again have AuthorizeViews or other controls that subscribe this CascadingValue as child content, the subscriber collection is changed asynchronously and you get the "Collection was modified; enumeration operation may not execute." exception. In my eyes the collections need to be copied before you enumerate so this code block gets safe. I will revert to the old school CascadingAuthenticationState control until this is fixed. This bug was added in .NET 8 and crashes/affects many projects as you will find googling.

Expected Behavior

Enumeration of the collection in a async/parallel/thread safe way and not getting exceptions if you nest controls that use the same cascading value.

Steps To Reproduce

Use AddCascadingAuthenticationState and nest some AuthorizeViews.

Exceptions (if any)

Exception Message: Collection was modified; enumeration operation may not execute.
Exception StackTrace:
at bool System.Collections.Generic.List+Enumerator.MoveNextRare()
at Task Microsoft.AspNetCore.Components.CascadingValueSource.NotifyChangedAsync()+() => { }
at Task Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContextDispatcher.InvokeAsync(Action workItem)
at Task Microsoft.AspNetCore.Components.CascadingValueSource.NotifyChangedAsync()
at void Microsoft.Extensions.DependencyInjection.CascadingAuthenticationStateServiceCollectionExtensions+AuthenticationStateCascadingValueSource.HandleAuthenticationStateChanged(Task newAuthStateTask)

.NET Version

8.0.302

Anything else?

No response

Metadata

Metadata

Assignees

Labels

area-blazorIncludes: Blazor, Razor ComponentsbugThis issue describes a behavior which is not expected - a bug.

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions