generated from nventive/Template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCancelPreviousCommandStrategy.cs
67 lines (58 loc) · 1.79 KB
/
CancelPreviousCommandStrategy.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Chinook.DynamicMvvm
{
public static partial class DynamicCommandStrategyExtensions
{
/// <summary>
/// Will cancel the previous command execution when executing the command.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns><see cref="IDynamicCommandBuilder"/></returns>
public static IDynamicCommandBuilder CancelPrevious(this IDynamicCommandBuilder builder)
=> builder.WithStrategy(new CancelPreviousCommandStrategy());
}
/// <summary>
/// This <see cref="DelegatingCommandStrategy"/> will cancel the previous command execution when executing the command.
/// </summary>
public class CancelPreviousCommandStrategy : DelegatingCommandStrategy
{
private CancellationTokenSource _cancellationTokenSource;
/// <summary>
/// Initializes a new instance of the <see cref="CancelPreviousCommandStrategy"/> class.
/// </summary>
public CancelPreviousCommandStrategy()
{
}
/// <inheritdoc />
public override async Task Execute(CancellationToken ct, object parameter, IDynamicCommand command)
{
TryCancelExecution();
_cancellationTokenSource = new CancellationTokenSource();
using (ct.Register(TryCancelExecution))
{
await base.Execute(_cancellationTokenSource.Token, parameter, command);
}
}
/// <summary>
/// Will cancel the current execution if any.
/// </summary>
private void TryCancelExecution()
{
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
}
}
/// <inheritdoc />
public override void Dispose()
{
TryCancelExecution();
base.Dispose();
}
}
}