ObservableCollection updated from Controller in Blazor causing error Cannot change ObservableCollection during a CollectionChanged event.

Hi, I am trying to update a SfGrid using an ObservableCollection that is being updated from a WebAPI controller in a Blazor project. I have this notification service to hold the ObservableCollection so I can inject this into the controller and the page with the SfGrid.

public interface INotificationService
{
    void AddNotification(Notification notification);
}
public class NotificationService
{
    public ObservableCollection<Notification> Notifications = new();
    public void AddNotification(Notification notification)
    {
        if (Notifications.Count > 20)
            Notifications.RemoveAt(20);
        Notifications.Insert(0, notification);
    }
}

I am adding this to the dependency container in startup.cs

builder.Services.AddSingleton<INotificationService>();

Then accessing this in the controller and making changes to the observable collection when new messages are received (this is from Dapr).

[ApiController]
[Route("[controller]")]
public class NotificationController : Controller
{
    [Topic("pubsub", "notifications")]
    public void Get(
        [FromBody] Notification notification,
        [FromServices] NotificationService notificationService,
        [FromServices] ILogger<NotificationController> log)
    {
        notificationService.AddNotification(notification);
    }
}

Then finally displaying this with the following component.

@inject NotificationService Service
<SfGrid TValue="Notification" DataSource="@Service.Notifications"></SfGrid>

This all seems to work fine but as I am sending multiple messages to the controller from different services I get an occasional exception thrown when messages arrive at the same time.

"Exception":"System.InvalidOperationException: Cannot change ObservableCollection during a CollectionChanged event.   at System.Collections.ObjectModel.ObservableCollection\u00601.CheckReentrancy() ...

Is there a better way to go about this?




1 Reply

RN Rahul Narayanasamy Syncfusion Team November 2, 2021 03:48 AM UTC

Hi Stuart, 

Greetings from Syncfusion. 

We have validated your query and we suspect that you are facing difficulties while updating the values while using Observable collection. Find the below links for your reference. 

Reference: 

Also, we have checked the reported error and the problem seems to be a general problem. Find the below links for more information.  


if you are still facing the problem, then could you please share more details(simple reproduceable sample). It will be helpful to validate and provide a better solution. 

Please let us know if you have any concerns. 

Regards, 
Rahul 


Loader.
Up arrow icon