Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

Commit abe70a3

Browse files
committed
A task that encapsulates multiple concurrent tasks
1 parent 6a41d52 commit abe70a3

File tree

2 files changed

+57
-5
lines changed

2 files changed

+57
-5
lines changed

src/GitHub.Api/Tasks/ActionTask.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,53 @@
55

66
namespace GitHub.Unity
77
{
8+
class TaskQueue : TaskBase
9+
{
10+
private TaskCompletionSource<bool> aggregateTask = new TaskCompletionSource<bool>();
11+
private readonly List<ITask> queuedTasks = new List<ITask>();
12+
private volatile bool isSuccessful = true;
13+
private volatile Exception exception;
14+
private int finishedTaskCount;
15+
16+
public TaskQueue() : base()
17+
{
18+
Initialize(aggregateTask.Task);
19+
}
20+
21+
public ITask Queue(ITask task)
22+
{
23+
task.OnEnd += TaskFinished;
24+
queuedTasks.Add(task);
25+
return this;
26+
}
27+
28+
public override ITask Start()
29+
{
30+
foreach (var task in queuedTasks)
31+
task.Start();
32+
return base.Start();
33+
}
34+
35+
private void TaskFinished(ITask task, bool success, Exception ex)
36+
{
37+
var count = Interlocked.Increment(ref finishedTaskCount);
38+
isSuccessful &= success;
39+
if (!success)
40+
exception = ex;
41+
if (count == queuedTasks.Count)
42+
{
43+
if (isSuccessful)
44+
{
45+
aggregateTask.TrySetResult(true);
46+
}
47+
else
48+
{
49+
aggregateTask.TrySetException(ex);
50+
}
51+
}
52+
}
53+
}
54+
855
class ActionTask : TaskBase
956
{
1057
protected Action<bool> Callback { get; }

src/GitHub.Api/Tasks/TaskBase.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,16 @@ protected TaskBase(CancellationToken token)
131131

132132
protected TaskBase(Task task)
133133
: this()
134+
{
135+
Initialize(task);
136+
}
137+
138+
protected TaskBase()
139+
{
140+
this.progress = new Progress(this);
141+
}
142+
143+
protected void Initialize(Task task)
134144
{
135145
Task = new Task(t =>
136146
{
@@ -158,11 +168,6 @@ protected TaskBase(Task task)
158168
}, task, Token, TaskCreationOptions.None);
159169
}
160170

161-
protected TaskBase()
162-
{
163-
this.progress = new Progress(this);
164-
}
165-
166171
public virtual T Then<T>(T nextTask, TaskRunOptions runOptions = TaskRunOptions.OnSuccess, bool taskIsTopOfChain = false)
167172
where T : ITask
168173
{

0 commit comments

Comments
 (0)