-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSTBootTimeout.cs
More file actions
31 lines (27 loc) · 922 Bytes
/
Copy pathSTBootTimeout.cs
File metadata and controls
31 lines (27 loc) · 922 Bytes
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace STBootLib
{
static class STBootTimeout
{
/* used for cancelling */
public static async Task<T> WithTimeout<T>(this Task<T> task, int timeout)
{
/* cancellation token source with timeout */
var cts = new CancellationTokenSource(timeout);
/* task completition source */
var tcs = new TaskCompletionSource<bool>();
using (cts.Token.Register(s =>
((TaskCompletionSource<bool>)s).TrySetResult(true), tcs)) {
/* timeout occured? or task finished normally? */
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException();
}
return await task;
}
}
}