-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskExtensions.cs
67 lines (61 loc) · 3.14 KB
/
TaskExtensions.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
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Extensions.ObjectExtensions;
namespace osu.Game.Extensions
{
public static class TaskExtensions
{
/// <summary>
/// Add a continuation to be performed only after the attached task has completed.
/// </summary>
/// <param name="task">The previous task to be awaited on.</param>
/// <param name="action">The action to run.</param>
/// <param name="cancellationToken">An optional cancellation token. Will only cancel the provided action, not the sequence.</param>
/// <returns>A task representing the provided action.</returns>
public static Task ContinueWithSequential(this Task task, Action action, CancellationToken cancellationToken = default) =>
task.ContinueWithSequential(() => Task.Run(action, cancellationToken), cancellationToken);
/// <summary>
/// Add a continuation to be performed only after the attached task has completed.
/// </summary>
/// <param name="task">The previous task to be awaited on.</param>
/// <param name="continuationFunction">The continuation to run. Generally should be an async function.</param>
/// <param name="cancellationToken">An optional cancellation token. Will only cancel the provided action, not the sequence.</param>
/// <returns>A task representing the provided action.</returns>
public static Task ContinueWithSequential(this Task task, Func<Task> continuationFunction, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<bool>();
task.ContinueWith(_ =>
{
// the previous task has finished execution or been cancelled, so we can run the provided continuation.
if (cancellationToken.IsCancellationRequested)
{
tcs.SetCanceled(cancellationToken);
}
else
{
continuationFunction().ContinueWith(continuationTask =>
{
if (cancellationToken.IsCancellationRequested || continuationTask.IsCanceled)
{
tcs.TrySetCanceled();
}
else if (continuationTask.IsFaulted)
{
tcs.TrySetException(continuationTask.Exception.AsNonNull());
}
else
{
tcs.TrySetResult(true);
}
}, cancellationToken: default);
}
}, cancellationToken: default);
// importantly, we are not returning the continuation itself but rather a task which represents its status in sequential execution order.
// this will not be cancelled or completed until the previous task has also.
return tcs.Task;
}
}
}