Skip to content

Instantly share code, notes, and snippets.

@yaegaki
Created October 25, 2018 13:07
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 yaegaki/4bd3082f70dd65dc58eeaed88aa24326 to your computer and use it in GitHub Desktop.
Save yaegaki/4bd3082f70dd65dc58eeaed88aa24326 to your computer and use it in GitHub Desktop.
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Threading;
using UniRx.Async;
namespace UniRx
{
public static class UniTaskCancellationTokenExtensions
{
private static readonly CancellationToken cancelledToken = new CancellationToken(true);
public static CancellationToken ToCancellationToken<T>(this UniTask<T> task)
{
if (task.IsCompleted)
{
return cancelledToken;
}
var source = new CancellationTokenSource();
Fire(source, task).Forget();
return source.Token;
}
public static CancellationToken ToCancellationToken(this UniTask task)
{
if (task.IsCompleted)
{
return cancelledToken;
}
var source = new CancellationTokenSource();
Fire(source, task).Forget();
return source.Token;
}
static async UniTaskVoid Fire<T>(CancellationTokenSource source, UniTask<T> task)
{
try
{
await task;
}
catch
{
}
source.Cancel();
}
static async UniTaskVoid Fire(CancellationTokenSource source, UniTask task)
{
try
{
await task;
}
catch
{
}
source.Cancel();
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment