What Is the Use of Observablecollection in .Net

What is the use of ObservableCollection in .net?

ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.

The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections

class Handler
{
private ObservableCollection<string> collection;

public Handler()
{
collection = new ObservableCollection<string>();
collection.CollectionChanged += HandleChange;
}

private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var x in e.NewItems)
{
// do something
}

foreach (var y in e.OldItems)
{
//do something
}
if (e.Action == NotifyCollectionChangedAction.Move)
{
//do something
}
}
}

Using ObservableCollection in ASP.NET

If you have a creative use for ObservableCollection outside of WPF, I don't see any reason you should not take advantage of it. Even Microsoft says:

Before implementing your own
collection, consider using
ObservableCollection<T> or one of
the existing collection classes, such
as List<T>, Collection<T>, and
BindingList<T>, among many others.

This article has an example of an ObservableCollection in WPF. However, the author makes this statement at the end of the article:

Although this application made use of
the binding support provided by the
ObservableCollection class and also
reacted to its CollectionChanged event
in order to update the user interface,
you needn't use the class this way. Because it notifies listeners that its
contents have changed, you can replace
any List or Collection instance that
you use with an ObservableCollection
instance (even if you're not creating
a WPF application
) and then hook up
event handlers to notify clients that
the collection's contents have
changed.

ObservableCollection vs. List

Interesting question, considering that both List and ObservableCollection implement IList<T> there isn't much of a difference there, ObservableCollection also implements INotifyCollectionChanged interface, which allows WPF to bind to it.

One of the main differences is that ObservableCollection does not have AddRange method, which might have some implications.

Also, I would not use ObservableCollection for places where I know I would not be binding to, for this reason, it is important to go over your design and make sure that you are taking the correct approach in separating layers of concern.

As far as the differences between Collection<T> and List<T> you can have a look here
Generic Lists vs Collection

What is the use of ObservableCollection in .net?

ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.

The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections

class Handler
{
private ObservableCollection<string> collection;

public Handler()
{
collection = new ObservableCollection<string>();
collection.CollectionChanged += HandleChange;
}

private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var x in e.NewItems)
{
// do something
}

foreach (var y in e.OldItems)
{
//do something
}
if (e.Action == NotifyCollectionChangedAction.Move)
{
//do something
}
}
}

BlockReentrancy in ObservableCollection T

An ObservableCollection implements INotifyCollectionChanged and so it has a CollectionChanged event. If there is a subscriber to this event, they could further modify the collection while the collection is already in the process of notification. Since the CollectionChanged event keeps track of exactly what changed, this interaction can get very messy.

As a result, the ObservableCollection allows, as a special case, a single subscriber of the CollectionChanged event to modify the collection from its handler. But it disallows modifying the collection from the CollectionChanged handler if there are two or more subscribers to the CollectionChanged event.

The pair of methods BlockReentrancy and CheckReentancy are used to implement this logic. The BlockReentrancy is used at the start of the OnCollectionChanged method and CheckReentancy is used in all methods that modify the collection.

How to update blazor view observable collection mvvm .net maui

Here's a very basic Razor routed component that demonstrates how to update the UI incrementally as a "Data Set" loads. I've kept it as simple as possible as you haven't provided enough detail for me to build a working model based on your code :-).

@page "/"
@using System.Diagnostics;
@using System.Text
@implements IDisposable

<h1>Slow Loading Record Set</h1>

@foreach (var message in this.Messages)
{
<div class="bg-dark text-white m-1 p-1">
@message
</div>
}

@code {
private List<string> Messages = new List<string>();
private bool cancel;

protected async override Task OnInitializedAsync()
{
this.Messages.Add($"Started Loading at {DateTime.Now.ToLongTimeString()}");
await LoadingSlowRecords();
this.Messages.Add($"Completed Loading at {DateTime.Now.ToLongTimeString()}");
}

private async Task LoadingSlowRecords()
{
for (var counter = 0; counter < 6; counter++)
{
if (cancel)
break;

await Task.Delay(3000);
this.Messages.Add($"New Record loaded at {DateTime.Now.ToLongTimeString()}");
Debug.WriteLine($"New Record loaded at {DateTime.Now.ToLongTimeString()}");
StateHasChanged();
}
}

public void Dispose()
{
Debug.WriteLine($"Dispose called at {DateTime.Now.ToLongTimeString()}");
cancel = true;
}
}


Related Topics



Leave a reply



Submit