2021-01-25 19:41:51 +08:00
|
|
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
|
|
|
|
// See the LICENCE file in the repository root for full licence text.
|
|
|
|
|
|
|
|
using System;
|
2021-01-26 21:47:37 +08:00
|
|
|
using System.Threading;
|
2021-01-25 19:41:51 +08:00
|
|
|
using System.Threading.Tasks;
|
2021-01-29 15:06:57 +08:00
|
|
|
using osu.Game.Extensions;
|
2021-01-25 19:41:51 +08:00
|
|
|
|
|
|
|
namespace osu.Game.Utils
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// A chain of <see cref="Task"/>s that run sequentially.
|
|
|
|
/// </summary>
|
|
|
|
public class TaskChain
|
|
|
|
{
|
2021-01-29 15:06:57 +08:00
|
|
|
private readonly object taskLock = new object();
|
|
|
|
|
|
|
|
private Task lastTaskInChain = Task.CompletedTask;
|
2021-01-25 19:41:51 +08:00
|
|
|
|
2021-01-25 19:58:05 +08:00
|
|
|
/// <summary>
|
|
|
|
/// Adds a new task to the end of this <see cref="TaskChain"/>.
|
|
|
|
/// </summary>
|
2021-01-26 21:47:37 +08:00
|
|
|
/// <param name="action">The action to be executed.</param>
|
|
|
|
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for this task. Does not affect further tasks in the chain.</param>
|
2021-01-25 19:58:05 +08:00
|
|
|
/// <returns>The awaitable <see cref="Task"/>.</returns>
|
2021-01-29 15:06:57 +08:00
|
|
|
public Task Add(Action action, CancellationToken cancellationToken = default)
|
2021-01-25 19:41:51 +08:00
|
|
|
{
|
2021-01-29 15:06:57 +08:00
|
|
|
lock (taskLock)
|
|
|
|
return lastTaskInChain = lastTaskInChain.ContinueWithSequential(action, cancellationToken);
|
|
|
|
}
|
2021-01-27 00:20:50 +08:00
|
|
|
|
2021-01-29 15:06:57 +08:00
|
|
|
/// <summary>
|
|
|
|
/// Adds a new task to the end of this <see cref="TaskChain"/>.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="task">The task to be executed.</param>
|
|
|
|
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for this task. Does not affect further tasks in the chain.</param>
|
|
|
|
/// <returns>The awaitable <see cref="Task"/>.</returns>
|
|
|
|
public Task Add(Func<Task> task, CancellationToken cancellationToken = default)
|
|
|
|
{
|
|
|
|
lock (taskLock)
|
|
|
|
return lastTaskInChain = lastTaskInChain.ContinueWithSequential(task, cancellationToken);
|
2021-01-25 19:41:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|