Update UniTaskExtensions.cs

Added an extension to run single-instance unitasks using CancellationTokenSourceReferences

This avoids running several instances of  unitasks using the same CancellationToenSource reference
pull/173/head
Extrys 2020-09-20 14:42:55 +02:00 committed by GitHub
parent 2bf9f4f062
commit 3eb14dfe4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 0 deletions

View File

@ -235,6 +235,16 @@ namespace Cysharp.Threading.Tasks
return new UniTask<T>(new WithCancellationSource<T>(task, cancellationToken), 0); return new UniTask<T>(new WithCancellationSource<T>(task, cancellationToken), 0);
} }
/// <summary>
/// Cancels last running instance to ensure there are not 2 or more instances of this UniTask running and regenerates the token source
/// </summary>
public static UniTask WithLastInstanceCancellation(this UniTask task, ref CancellationTokenSource cancellationTokenSource)
{
cancellationTokenSource.Cancel();
cancellationTokenSource = new CancellationTokenSource();
return task.WithCancellation(cancellationTokenSource.Token);
}
sealed class WithCancellationSource : IUniTaskSource sealed class WithCancellationSource : IUniTaskSource
{ {
static readonly Action<object> cancellationCallbackDelegate = CancellationCallback; static readonly Action<object> cancellationCallbackDelegate = CancellationCallback;