-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathMainViewModel.cs
70 lines (57 loc) · 2.35 KB
/
MainViewModel.cs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
namespace Catel.Examples.TaskCommand.ViewModels
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Models;
using MVVM;
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
LoadSomethingCommand = new ProgressiveTaskCommand<PercentProgress>(LoadSomethingAsync, reportProgress: ReportLoadSomethingProgress);
Title = "Task command example";
}
public int LoadPercent { get; set; }
public string StatusText { get; set; }
public ProgressiveTaskCommand<PercentProgress> LoadSomethingCommand { get; private set; }
private static async Task LoadSomethingAsync(CancellationToken cancellationToken, IProgress<PercentProgress> progress)
{
var sw = Stopwatch.StartNew();
var isCanceled = false;
var percent = 0;
try
{
var rnd = new Random();
var fast = rnd.Next(0, 10) > 5;
for (percent = 0; percent < 100; percent++)
{
cancellationToken.ThrowIfCancellationRequested();
// Reporting progress.
progress.Report(new PercentProgress(percent, string.Format("Loading [{0}%]...", percent)));
// Simulating a long running process.
var delayMilliseconds = rnd.Next(percent, percent + 50) < 50 || percent > 90
? rnd.Next(fast ? 1 : 100, fast ? 10 : 500)
: rnd.Next(10, 100);
await Task.Delay(delayMilliseconds, cancellationToken);
}
}
catch (OperationCanceledException)
{
isCanceled = true;
}
finally
{
sw.Stop();
// Reporting progress.
progress.Report(new PercentProgress(percent, isCanceled ? string.Format("Loaded {0:D}%. Canceled after {1:F2}s.", percent, sw.Elapsed.TotalSeconds) : string.Format("Loaded {0:D}% in {1:F2}s.", percent, sw.Elapsed.TotalSeconds)));
}
}
private void ReportLoadSomethingProgress(PercentProgress progress)
{
LoadPercent = progress.Percent;
StatusText = progress.Status;
}
}
}