-
Notifications
You must be signed in to change notification settings - Fork 750
/
Copy pathTaskUtils.cs
56 lines (49 loc) · 1.63 KB
/
TaskUtils.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace NetMQ.Tests
{
internal class TaskUtils
{
internal static async Task PollUntil(Func<bool> condition, TimeSpan timeout)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);
await PollUntil(condition, cts.Token);
}
internal static async Task PollUntil(Func<bool> condition, CancellationToken ct = default)
{
try
{
while (!condition())
{
await Task.Delay(25, ct).ConfigureAwait(true);
}
}
catch (TaskCanceledException)
{
// Task was cancelled. Ignore exception and return.
}
}
internal static bool WaitAll(IEnumerable<Task> tasks, TimeSpan timeout)
{
PollUntil(() => tasks.All(t => t.IsCompleted), timeout).Wait();
return tasks.All(t => t.Status == TaskStatus.RanToCompletion);
}
internal static void WaitAll(IEnumerable<Task> tasks)
{
PollUntil(() => tasks.All(t => t.IsCompleted), Timeout.InfiniteTimeSpan).Wait();
}
internal static bool Wait(Task task, TimeSpan timeout)
{
PollUntil(() => task.IsCompleted, timeout).Wait();
return task.Status == TaskStatus.RanToCompletion;
}
internal static void Wait(Task task)
{
PollUntil(() => task.IsCompleted, Timeout.InfiniteTimeSpan).Wait();
}
}
}