-
Notifications
You must be signed in to change notification settings - Fork 317
Expand file tree
/
Copy pathTaskHelpers.cs
More file actions
78 lines (70 loc) · 2.8 KB
/
Copy pathTaskHelpers.cs
File metadata and controls
78 lines (70 loc) · 2.8 KB
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
namespace NEventStore
{
internal static class TaskHelpers
{
internal static Task Delay(double milliseconds, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
TimerCallback callback = (_) => tcs.TrySetResult(true);
#pragma warning disable IDE0067 // Dispose objects before losing scope
var timer = new Timer(callback, null, 0, Convert.ToInt32(milliseconds));
#pragma warning restore IDE0067 // Dispose objects before losing scope
CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.Register(() =>
{
timer.Dispose();
tcs.TrySetCanceled();
});
return tcs.Task.ContinueWith(_ =>
{
cancellationTokenRegistration.Dispose();
timer.Dispose();
}, TaskContinuationOptions.ExecuteSynchronously);
}
public static void WhenCompleted<T>(this Task<T> task, Action<Task<T>> onComplete, Action<Task<T>> onFaulted, bool execSync = false)
{
if (task.IsCompleted)
{
if (task.IsFaulted)
{
onFaulted.Invoke(task);
return;
}
onComplete.Invoke(task);
return;
}
task.ContinueWith(
onComplete,
execSync ?
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion :
TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(
onFaulted,
execSync ?
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted :
TaskContinuationOptions.OnlyOnFaulted);
}
public static void WhenCompleted(this Task task, Action<Task> onComplete, Action<Task> onFaulted, bool execSync = false)
{
if (task.IsCompleted)
{
if (task.IsFaulted)
{
onFaulted.Invoke(task);
return;
}
onComplete.Invoke(task);
return;
}
task.ContinueWith(
onComplete,
execSync ?
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion :
TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(
onFaulted,
execSync ?
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted :
TaskContinuationOptions.OnlyOnFaulted);
}
}
}