This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathTaskTimeoutExtensions.cs
136 lines (125 loc) · 5.02 KB
/
TaskTimeoutExtensions.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// Task timeout helper based on http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx
/// </summary>
namespace System.Threading.Tasks
{
public static class TaskTimeoutExtensions
{
public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
{
throw new OperationCanceledException(cancellationToken);
}
await task; // already completed; propagate any exception
}
}
public static async Task TimeoutAfter(this Task task, int millisecondsTimeout)
{
var cts = new CancellationTokenSource();
if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout, cts.Token)).ConfigureAwait(false))
{
cts.Cancel();
await task.ConfigureAwait(false);
}
else
{
throw new TimeoutException($"Task timed out after {millisecondsTimeout}ms");
}
}
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, int millisecondsTimeout)
{
var cts = new CancellationTokenSource();
if (task == await Task<TResult>.WhenAny(task, Task<TResult>.Delay(millisecondsTimeout, cts.Token)).ConfigureAwait(false))
{
cts.Cancel();
return await task.ConfigureAwait(false);
}
else
{
throw new TimeoutException($"Task timed out after {millisecondsTimeout}ms");
}
}
public static async Task WhenAllOrAnyFailed(this Task[] tasks, int millisecondsTimeout)
{
var cts = new CancellationTokenSource();
Task task = tasks.WhenAllOrAnyFailed();
if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout, cts.Token)).ConfigureAwait(false))
{
cts.Cancel();
await task.ConfigureAwait(false);
}
else
{
throw new TimeoutException($"{nameof(WhenAllOrAnyFailed)} timed out after {millisecondsTimeout}ms");
}
}
public static async Task WhenAllOrAnyFailed(this Task[] tasks)
{
try
{
await WhenAllOrAnyFailedCore(tasks).ConfigureAwait(false);
}
catch
{
// Wait a bit to allow other tasks to complete so we can include their exceptions
// in the error we throw.
using (var cts = new CancellationTokenSource())
{
await Task.WhenAny(
Task.WhenAll(tasks),
Task.Delay(3_000, cts.Token)).ConfigureAwait(false); // arbitrary delay; can be dialed up or down in the future
}
var exceptions = new List<Exception>();
foreach (Task t in tasks)
{
switch (t.Status)
{
case TaskStatus.Faulted: exceptions.Add(t.Exception); break;
case TaskStatus.Canceled: exceptions.Add(new TaskCanceledException(t)); break;
}
}
Debug.Assert(exceptions.Count > 0);
if (exceptions.Count > 1)
{
throw new AggregateException(exceptions);
}
throw;
}
}
private static Task WhenAllOrAnyFailedCore(this Task[] tasks)
{
int remaining = tasks.Length;
var tcs = new TaskCompletionSource<bool>();
foreach (Task t in tasks)
{
t.ContinueWith(a =>
{
if (a.IsFaulted)
{
tcs.TrySetException(a.Exception.InnerExceptions);
Interlocked.Decrement(ref remaining);
}
else if (a.IsCanceled)
{
tcs.TrySetCanceled();
Interlocked.Decrement(ref remaining);
}
else if (Interlocked.Decrement(ref remaining) == 0)
{
tcs.TrySetResult(true);
}
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
return tcs.Task;
}
}
}