Skip to content

Commit

Permalink
Add polyfill for CancellationTokenSource.CancelAsync() (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tyrrrz authored Jan 11, 2024
1 parent a7985de commit 07574cd
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
22 changes: 22 additions & 0 deletions PolyShim.Tests/Net80/CancellationTokenSourceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;

namespace PolyShim.Tests.Net80;

public class CancellationTokenSourceTests
{
[Fact]
public async Task CancelAsync_Test()
{
// Arrange
using var cts = new CancellationTokenSource();

// Act
await cts.CancelAsync();

// Assert
cts.IsCancellationRequested.Should().BeTrue();
}
}
30 changes: 30 additions & 0 deletions PolyShim/Net80/CancellationTokenSource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#if FEATURE_TASK
#if (NETCOREAPP && !NET8_0_OR_GREATER) || (NETFRAMEWORK) || (NETSTANDARD)
#nullable enable
// ReSharper disable RedundantUsingDirective
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable PartialTypeWithSinglePart

using System.Collections;
using System.Threading;
using System.Threading.Tasks;

internal static partial class PolyfillExtensions
{
// https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.cancelasync
public static Task CancelAsync(this CancellationTokenSource cts)
{
#if (NETFRAMEWORK && !NET45_OR_GREATER)
return Task.Factory.StartNew(() => cts.Cancel());
#elif (NETFRAMEWORK && !NET46_OR_GREATER) || (NETSTANDARD && !NETSTANDARD1_3_OR_GREATER)
cts.Cancel();
return Task.FromResult<object?>(null);
#else
cts.Cancel();
return Task.CompletedTask;
#endif
}
}
#endif
#endif

0 comments on commit 07574cd

Please sign in to comment.