Why this code? It won't help unless you have thousands of files. There is a cost to marshall methods to a remote thread and back. Every change to the
ObservableCollection
must happen on the UI thread.
If you do have thousands of files, then you would need to batch changes and then add to the
ObservableCollection
with the batch rather than individually. The optimal solution is to roll your own
ObservableCollection
that does not trigger a
CollectionChanged
event for each individual change. Here is an example of how to do this:
GitHub - ENikS/ObservableCollectionEx[
^]
The cheap and nasty way to make synchronous run in a thread using TPL is to use
Task.Run Method (System.Threading.Tasks) | Microsoft Learn[
^].
As mentioned above, you may be running on a seperate thread to the UI. So you will need to marshall back to the UI thread to update the
ObservableCollection
as it is not thread-safe. Here is a helper class:
namespace System.Windows.Threading;
public static class DispatcherHelper
{
public static void Execute(Action action)
{
if (Application.Current is null || Application.Current.Dispatcher is null)
return;
Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, action);
}
}
To use, from the remote thread where your code is running and want to update the
ObservableCollection
, you would use it like this:
DispatcherHelper.Execute(() => MyCollection.Add(DataModel));