Skip to content

Instantly share code, notes, and snippets.

@felipeslongo
Last active April 24, 2019 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeslongo/2aa4cc571bbbc926eb5d70bca6d1573a to your computer and use it in GitHub Desktop.
Save felipeslongo/2aa4cc571bbbc926eb5d70bca6d1573a to your computer and use it in GitHub Desktop.
Utility to renew a cancellation token correctly
using System.Threading;
namespace Core.Extensions
{
public static class CancellationTokenSourceRenew
{
public static CancellationTokenSource Renew(this CancellationTokenSource @this)
{
Cancel(@this);
return new CancellationTokenSource();
}
private static void Cancel(CancellationTokenSource @this)
{
try
{
@this?.Cancel();
@this?.Dispose();
}
catch(ObjectDisposedException){/*Segue o jogo*/}
}
}
}
using System.Threading;
using Core.Extensions;
using NUnit.Framework;
namespace Core.Tests.Extensions
{
[TestFixture]
public class CancellationTokenSourceRenewTests
{
[Test]
public void DeveCancelarOTokenAtualAoRenovar()
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
tokenSource.Renew();
Assert.IsTrue(token.IsCancellationRequested);
Assert.IsTrue(tokenSource.IsCancellationRequested);
}
[Test]
public void DeveRetornarUmaNovaInstancia()
{
var tokenSource = new CancellationTokenSource();
var novoTokenSource = tokenSource.Renew();
Assert.AreNotSame(tokenSource, novoTokenSource);
}
[Test]
public void NaoDeveRetornarUmTokenSourceCancelado()
{
var tokenSource = new CancellationTokenSource();
var novoTokenSource = tokenSource.Renew();
Assert.IsFalse(novoTokenSource.Token.IsCancellationRequested);
Assert.IsFalse(novoTokenSource.IsCancellationRequested);
}
[Test]
public void DeveSerIdempotente()
{
var tokenSource = new CancellationTokenSource();
tokenSource.Renew();
tokenSource.Renew();
}
}
}
@felipeslongo
Copy link
Author

Implemented Idempotence principle

@felipeslongo
Copy link
Author

tests implemented

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment