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?