-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e0d34ab
commit f84f32d
Showing
2 changed files
with
48 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
// Copyright Bastian Eicher | ||
// Licensed under the MIT License | ||
|
||
#if !NET20 && !NET40 | ||
using System.Threading.Tasks; | ||
|
||
namespace NanoByte.Common.Threading; | ||
|
||
public static class TaskExtensions | ||
{ | ||
/// <summary> | ||
/// Gets a <see cref="Task"/> that will complete when <paramref name="task"/> completes or when the specified <paramref name="cancellationToken"/> has cancellation requested. | ||
/// </summary> | ||
/// <exception cref="OperationCanceledException">Cancellation has been requested.</exception> | ||
public static async Task WaitAsync(this Task task, CancellationToken cancellationToken) | ||
#if NETFRAMEWORK | ||
{ | ||
var cancellationCompletion = new TaskCompletionSource<bool>(); | ||
var token = cancellationToken; | ||
using (token.Register(() => cancellationCompletion.SetCanceled())) | ||
await Task.WhenAny(task, cancellationCompletion.Task); | ||
token.ThrowIfCancellationRequested(); | ||
await task; | ||
} | ||
#else | ||
=> await task.WaitAsync(cancellationToken); | ||
#endif | ||
|
||
/// <summary> | ||
/// Gets a <see cref="Task"/> that will complete when <paramref name="task"/> completes or when the specified <paramref name="cancellationToken"/> has cancellation requested. | ||
/// </summary> | ||
/// <exception cref="OperationCanceledException">Cancellation has been requested.</exception> | ||
public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken) | ||
#if NETFRAMEWORK | ||
{ | ||
var cancellationCompletion = new TaskCompletionSource<bool>(); | ||
var token = cancellationToken; | ||
using (token.Register(() => cancellationCompletion.SetCanceled())) | ||
await Task.WhenAny(task, cancellationCompletion.Task); | ||
token.ThrowIfCancellationRequested(); | ||
return await task; | ||
} | ||
#else | ||
=> await task.WaitAsync(cancellationToken); | ||
#endif | ||
} | ||
#endif |