aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Scripting/Tango.Scripting.Test/App.xaml
blob: 731c7f907b1b9aabf1ae8f8d38e67ba9979e9927 (plain)
1
2
3
4
5
6
7
8
9
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

public static class ObservableCollectionExtensions
{
    public static ObservableCollection<T> ToObservableCollectionAsyncIdle<T>(this ObservableCollection<T> source)
    {
        var copy = source.ToList();
        ObservableCollection<T> result = new ObservableCollection<T>();

        foreach (var item in copy)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                result.Add(item);
            }), DispatcherPriority.ContextIdle);
        }

        return result;
    }

    public static void ReloadAsyncIdle<T>(this ObservableCollection<T> source, Action<int, int> onProgress, Action onComplete = null)
    {
        var copy = source.ToList();
        source.Clear();

        int count = copy.Count;
        int completed = 0;

        foreach (var item in copy)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                source.Add(item);
                completed++;

                onProgress?.Invoke(completed, count);

                if (completed == count)
                {
                    onComplete?.Invoke();
                }
            }), DispatcherPriority.ContextIdle);
        }
    }
}