-
Notifications
You must be signed in to change notification settings - Fork 22
/
Helpers.cs
41 lines (38 loc) · 1.51 KB
/
Helpers.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
// <copyright file="Helpers.cs" company="Zhaoquan Huang">
// Copyright (c) Zhaoquan Huang. All rights reserved
// </copyright>
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Zhaobang.FtpServer
{
/// <summary>
/// Static class that stores some helpers.
/// </summary>
internal static class Helpers
{
/// <summary>
/// Gets the task to wait for the original task or throws an exception when trying to cancel.
/// The original task will not and can not be terminated.
/// </summary>
/// <typeparam name="T">The typeparam of the source task.</typeparam>
/// <param name="task">The task to wait.</param>
/// <param name="cancellationToken">The cancellation token to cancel the action.</param>
/// <returns>The task to wait until the original task finishes.</returns>
public static async Task<T> WithCancellation<T>(this Task<T> 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))
{
throw new OperationCanceledException(cancellationToken);
}
}
return await task;
}
}
}