forked from gitextensions/gitextensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncLoader.cs
171 lines (143 loc) · 4.65 KB
/
AsyncLoader.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
using System;
using System.Threading;
using System.Threading.Tasks;
using GitUI;
using JetBrains.Annotations;
using Microsoft.VisualStudio.Threading;
namespace GitCommands
{
public sealed class AsyncLoader : IDisposable
{
public event EventHandler<AsyncErrorEventArgs> LoadingError;
private readonly CancellationTokenSequence _cancellationSequence = new CancellationTokenSequence();
private int _disposed;
/// <summary>
/// Gets and sets an amount of time to delay calling <c>loadContent</c> actions after a call to one of the <c>Load</c> overloads.
/// </summary>
/// <remarks>
/// Defaults to <see cref="TimeSpan.Zero"/>.
/// </remarks>
public TimeSpan Delay { get; set; }
public Task LoadAsync(Action loadContent, Action onLoaded)
{
return LoadAsync(token => loadContent(), onLoaded);
}
public async Task LoadAsync(Action<CancellationToken> loadContent, Action onLoaded)
{
await LoadAsync(
(token) =>
{
loadContent(token);
return string.Empty;
},
_ => onLoaded());
}
public Task<T> LoadAsync<T>(Func<T> loadContent, Action<T> onLoaded)
{
return LoadAsync(token => loadContent(), onLoaded);
}
[ItemCanBeNull]
public async Task<T> LoadAsync<T>(Func<CancellationToken, T> loadContent, Action<T> onLoaded)
{
if (Volatile.Read(ref _disposed) != 0)
{
throw new ObjectDisposedException(nameof(AsyncLoader));
}
// Stop any prior operation
Cancel();
// Create a new cancellation token
var token = _cancellationSequence.Next();
T result;
try
{
// Defer the load operation if requested
if (Delay > TimeSpan.Zero)
{
await Task.Delay(Delay, token).ConfigureAwait(false);
}
else
{
await TaskScheduler.Default.SwitchTo(alwaysYield: true);
}
// Bail early if cancelled, returning default value for type
if (token.IsCancellationRequested)
{
result = default;
}
else
{
// Load content
result = loadContent(token);
}
}
catch (Exception e)
{
if (e is OperationCanceledException && token.IsCancellationRequested)
{
return default;
}
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!OnLoadingError(e))
{
throw;
}
return default;
}
try
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(token);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
}
// Invoke continuation unless cancelled
if (!token.IsCancellationRequested)
{
try
{
onLoaded(result);
}
catch (Exception e)
{
if (!OnLoadingError(e))
{
throw;
}
return default;
}
}
return result;
}
private bool OnLoadingError(Exception exception)
{
var args = new AsyncErrorEventArgs(exception);
LoadingError?.Invoke(this, args);
return args.Handled;
}
public void Cancel()
{
if (Volatile.Read(ref _disposed) != 0)
{
throw new ObjectDisposedException(nameof(AsyncLoader));
}
_cancellationSequence.CancelCurrent();
}
public void Dispose()
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0)
{
return;
}
_cancellationSequence?.Dispose();
}
}
public sealed class AsyncErrorEventArgs : EventArgs
{
public Exception Exception { get; }
public bool Handled { get; set; } = true;
public AsyncErrorEventArgs(Exception exception)
{
Exception = exception;
}
}
}