Last active
April 24, 2019 16:44
-
-
Save felipeslongo/2aa4cc571bbbc926eb5d70bca6d1573a to your computer and use it in GitHub Desktop.
Utility to renew a cancellation token correctly
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
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*/} | |
} | |
} | |
} |
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
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(); | |
} | |
} | |
} |
tests implemented
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Implemented Idempotence principle