aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.Common/ExtensionMethods/ObservableCollectionExtensions.cs
blob: c539273d924361a8ed3622b23011b51a12ea4143 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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);
        }
    }
}