UniTask/Assets/UniRx.Async/UniTaskCompletionSource.cs

650 lines
19 KiB
C#
Raw Normal View History

2019-05-19 23:14:47 +08:00
#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;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
2020-04-18 04:07:59 +08:00
using System.Runtime.InteropServices;
2019-05-19 23:14:47 +08:00
using System.Threading;
using UniRx.Async.Internal;
namespace UniRx.Async
{
public interface IResolvePromise
{
void SetResult();
2019-05-19 23:14:47 +08:00
}
public interface IResolvePromise<T>
{
void SetResult(T value);
2019-05-19 23:14:47 +08:00
}
public interface IRejectPromise
{
void SetException(Exception exception);
2019-05-19 23:14:47 +08:00
}
public interface ICancelPromise
{
void SetCanceled(CancellationToken cancellationToken = default);
2019-05-19 23:14:47 +08:00
}
public interface IPromise<T> : IResolvePromise<T>, IRejectPromise, ICancelPromise
{
}
public interface IPromise : IResolvePromise, IRejectPromise, ICancelPromise
{
}
2020-04-18 04:07:59 +08:00
[StructLayout(LayoutKind.Auto)]
public struct UniTaskCompletionSourceCore<TResult>
{
// Struct Size: TResult + (8 + 2 + 1 + 1 + 8 + 8)
TResult result;
2020-04-20 07:35:06 +08:00
object error; // ExceptionDispatchInfo or OperationCanceledException
2020-04-18 04:07:59 +08:00
short version;
bool hasUnhandledError;
2020-04-21 12:36:23 +08:00
int completedCount; // 0: completed == false
2020-04-18 04:07:59 +08:00
Action<object> continuation;
object continuationState;
public void Reset()
{
ReportUnhandledError();
unchecked
{
version += 1; // incr version.
}
2020-04-21 12:36:23 +08:00
completedCount = 0;
2020-04-18 04:07:59 +08:00
result = default;
error = null;
hasUnhandledError = false;
continuation = null;
continuationState = null;
}
void ReportUnhandledError()
{
if (hasUnhandledError)
{
try
{
if (error is OperationCanceledException oc)
{
UniTaskScheduler.PublishUnobservedTaskException(oc);
}
else if (error is ExceptionDispatchInfo ei)
{
UniTaskScheduler.PublishUnobservedTaskException(ei.SourceException);
}
}
catch
{
}
}
}
/// <summary>Completes with a successful result.</summary>
/// <param name="result">The result.</param>
2020-04-21 12:36:23 +08:00
public bool TrySetResult(TResult result)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
if (Interlocked.Increment(ref completedCount) == 1)
{
// setup result
this.result = result;
if (continuation != null || Interlocked.CompareExchange(ref this.continuation, UniTaskCompletionSourceCoreShared.s_sentinel, null) != null)
{
continuation(continuationState);
return true;
}
}
return false;
2020-04-18 04:07:59 +08:00
}
/// <summary>Completes with an error.</summary>
/// <param name="error">The exception.</param>
2020-04-21 12:36:23 +08:00
public bool TrySetException(Exception error)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
if (Interlocked.Increment(ref completedCount) == 1)
{
// setup result
this.hasUnhandledError = true;
this.error = ExceptionDispatchInfo.Capture(error);
if (continuation != null || Interlocked.CompareExchange(ref this.continuation, UniTaskCompletionSourceCoreShared.s_sentinel, null) != null)
{
continuation(continuationState);
return true;
}
}
return false;
2020-04-18 04:07:59 +08:00
}
2020-04-21 12:36:23 +08:00
public bool TrySetCanceled(CancellationToken cancellationToken = default)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
if (Interlocked.Increment(ref completedCount) == 1)
{
// setup result
this.hasUnhandledError = true;
this.error = new OperationCanceledException(cancellationToken);
if (continuation != null || Interlocked.CompareExchange(ref this.continuation, UniTaskCompletionSourceCoreShared.s_sentinel, null) != null)
{
continuation(continuationState);
return true;
}
}
return false;
2020-04-18 04:07:59 +08:00
}
/// <summary>Gets the operation version.</summary>
public short Version => version;
/// <summary>Gets the status of the operation.</summary>
/// <param name="token">Opaque value that was provided to the <see cref="UniTask"/>'s constructor.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2020-04-20 07:35:06 +08:00
public UniTaskStatus GetStatus(short token)
2020-04-18 04:07:59 +08:00
{
ValidateToken(token);
2020-04-21 12:36:23 +08:00
return (continuation == null || (completedCount == 0)) ? UniTaskStatus.Pending
2020-04-20 07:35:06 +08:00
: (error == null) ? UniTaskStatus.Succeeded
: (error is OperationCanceledException) ? UniTaskStatus.Canceled
: UniTaskStatus.Faulted;
2020-04-18 04:07:59 +08:00
}
/// <summary>Gets the status of the operation without token validation.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2020-04-20 07:35:06 +08:00
public UniTaskStatus UnsafeGetStatus()
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
return (continuation == null || (completedCount == 0)) ? UniTaskStatus.Pending
2020-04-20 07:35:06 +08:00
: (error == null) ? UniTaskStatus.Succeeded
: (error is OperationCanceledException) ? UniTaskStatus.Canceled
: UniTaskStatus.Faulted;
2020-04-18 04:07:59 +08:00
}
/// <summary>Gets the result of the operation.</summary>
/// <param name="token">Opaque value that was provided to the <see cref="UniTask"/>'s constructor.</param>
// [StackTraceHidden]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TResult GetResult(short token)
{
ValidateToken(token);
2020-04-21 12:36:23 +08:00
if (!(completedCount == 0))
2020-04-18 04:07:59 +08:00
{
throw new InvalidOperationException("not yet completed.");
}
if (error != null)
{
hasUnhandledError = false;
if (error is OperationCanceledException oce)
{
throw oce;
}
else if (error is ExceptionDispatchInfo edi)
{
edi.Throw();
}
throw new InvalidOperationException("Critical: invalid exception type was held.");
}
return result;
}
/// <summary>Schedules the continuation action for this operation.</summary>
/// <param name="continuation">The continuation to invoke when the operation has completed.</param>
/// <param name="state">The state object to pass to <paramref name="continuation"/> when it's invoked.</param>
/// <param name="token">Opaque value that was provided to the <see cref="UniTask"/>'s constructor.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void OnCompleted(Action<object> continuation, object state, short token /*, ValueTaskSourceOnCompletedFlags flags */)
{
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
ValidateToken(token);
/* no use ValueTaskSourceOnCOmpletedFlags, always no capture ExecutionContext and SynchronizationContext. */
2020-04-21 12:36:23 +08:00
/*
PatternA: GetStatus=Pending => OnCompleted => TrySet*** => GetResult
PatternB: TrySet*** => GetStatus=!Pending => GetResult
PatternC: GetStatus=Pending => TrySet/OnCompleted(race condition) => GetResult
C.1: win OnCompleted -> TrySet invoke saved continuation
C.2: win TrySet -> should invoke continuation here.
*/
// not set continuation yet.
2020-04-18 04:07:59 +08:00
object oldContinuation = this.continuation;
if (oldContinuation == null)
{
continuationState = state;
oldContinuation = Interlocked.CompareExchange(ref this.continuation, continuation, null);
}
if (oldContinuation != null)
{
2020-04-21 12:36:23 +08:00
// already running continuation in TrySet.
// It will cause call OnCompleted multiple time, invalid.
2020-04-18 04:07:59 +08:00
if (!ReferenceEquals(oldContinuation, UniTaskCompletionSourceCoreShared.s_sentinel))
{
2020-04-21 12:36:23 +08:00
throw new InvalidOperationException();
2020-04-18 04:07:59 +08:00
}
continuation(state);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidateToken(short token)
{
if (token != version)
{
throw new InvalidOperationException("token version is not matched.");
}
}
}
internal static class UniTaskCompletionSourceCoreShared // separated out of generic to avoid unnecessary duplication
{
internal static readonly Action<object> s_sentinel = CompletionSentinel;
private static void CompletionSentinel(object _) // named method to aid debugging
{
throw new InvalidOperationException("The sentinel delegate should never be invoked.");
}
}
public class UniTaskCompletionSource : IUniTaskSource, IPromise
2020-04-18 04:07:59 +08:00
{
UniTaskCompletionSourceCore<AsyncUnit> core;
bool handled = false;
public UniTaskCompletionSource()
2020-04-18 04:07:59 +08:00
{
TaskTracker2.TrackActiveTask(this, 2);
}
[Conditional("UNITY_EDITOR")]
2020-04-19 01:55:44 +08:00
internal void MarkHandled()
2020-04-18 04:07:59 +08:00
{
if (!handled)
{
handled = true;
TaskTracker2.RemoveTracking(this);
}
}
public UniTask Task
2020-04-18 04:07:59 +08:00
{
get
{
return new UniTask(this, core.Version);
2020-04-18 04:07:59 +08:00
}
}
public void Reset()
{
// Reset, re-active tracker
handled = false;
TaskTracker2.TrackActiveTask(this, 2);
core.Reset();
}
public void SetResult()
{
2020-04-21 12:36:23 +08:00
core.TrySetResult(AsyncUnit.Default);
2020-04-18 04:07:59 +08:00
}
2020-04-19 01:55:44 +08:00
public void SetCanceled(CancellationToken cancellationToken = default)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
core.TrySetCanceled(cancellationToken);
2020-04-18 04:07:59 +08:00
}
public void SetException(Exception exception)
{
2020-04-21 12:36:23 +08:00
core.TrySetException(exception);
2020-04-18 04:07:59 +08:00
}
public void GetResult(short token)
{
MarkHandled();
core.GetResult(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus GetStatus(short token)
2020-04-18 04:07:59 +08:00
{
return core.GetStatus(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus UnsafeGetStatus()
2020-04-18 04:07:59 +08:00
{
return core.UnsafeGetStatus();
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
~UniTaskCompletionSource()
2020-04-18 04:07:59 +08:00
{
// clear error information.
core.Reset();
}
}
public class AutoResetUniTaskCompletionSource : IUniTaskSource, IPromisePoolItem, IPromise
2020-04-18 04:07:59 +08:00
{
static readonly PromisePool<AutoResetUniTaskCompletionSource> pool = new PromisePool<AutoResetUniTaskCompletionSource>();
UniTaskCompletionSourceCore<AsyncUnit> core;
AutoResetUniTaskCompletionSource()
{
}
public static AutoResetUniTaskCompletionSource Create()
{
2020-04-18 21:11:40 +08:00
var value = pool.TryRent() ?? new AutoResetUniTaskCompletionSource();
TaskTracker2.TrackActiveTask(value, 2);
return value;
2020-04-18 04:07:59 +08:00
}
public static AutoResetUniTaskCompletionSource CreateFromCanceled(CancellationToken cancellationToken, out short token)
{
var source = Create();
2020-04-19 01:55:44 +08:00
source.SetCanceled(cancellationToken);
2020-04-18 04:07:59 +08:00
token = source.core.Version;
return source;
}
public static AutoResetUniTaskCompletionSource CreateFromException(Exception exception, out short token)
{
var source = Create();
source.SetException(exception);
token = source.core.Version;
return source;
}
public static AutoResetUniTaskCompletionSource CreateCompleted(out short token)
{
var source = Create();
source.SetResult();
token = source.core.Version;
return source;
}
public UniTask Task
2020-04-18 04:07:59 +08:00
{
get
{
return new UniTask(this, core.Version);
2020-04-18 04:07:59 +08:00
}
}
public void SetResult()
{
2020-04-21 12:36:23 +08:00
core.TrySetResult(AsyncUnit.Default);
2020-04-18 04:07:59 +08:00
}
2020-04-19 01:55:44 +08:00
public void SetCanceled(CancellationToken cancellationToken = default)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
core.TrySetCanceled(cancellationToken);
2020-04-18 04:07:59 +08:00
}
public void SetException(Exception exception)
{
2020-04-21 12:36:23 +08:00
core.TrySetException(exception);
2020-04-18 04:07:59 +08:00
}
public void GetResult(short token)
{
try
{
2020-04-18 21:11:40 +08:00
TaskTracker2.RemoveTracking(this);
2020-04-18 04:07:59 +08:00
core.GetResult(token);
}
finally
{
pool.TryReturn(this);
}
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus GetStatus(short token)
2020-04-18 04:07:59 +08:00
{
return core.GetStatus(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus UnsafeGetStatus()
2020-04-18 04:07:59 +08:00
{
return core.UnsafeGetStatus();
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
void IPromisePoolItem.Reset()
{
core.Reset();
}
~AutoResetUniTaskCompletionSource()
{
if (pool.TryReturn(this))
{
GC.ReRegisterForFinalize(this);
return;
}
}
}
public class UniTaskCompletionSource<T> : IUniTaskSource<T>, IPromise<T>
2020-04-18 04:07:59 +08:00
{
UniTaskCompletionSourceCore<T> core;
bool handled = false;
public UniTaskCompletionSource()
2020-04-18 04:07:59 +08:00
{
2020-04-18 21:11:40 +08:00
TaskTracker2.TrackActiveTask(this, 2);
2020-04-18 04:07:59 +08:00
}
[Conditional("UNITY_EDITOR")]
2020-04-19 01:55:44 +08:00
internal void MarkHandled()
2020-04-18 04:07:59 +08:00
{
if (!handled)
{
handled = true;
2020-04-18 21:11:40 +08:00
TaskTracker2.RemoveTracking(this);
2020-04-18 04:07:59 +08:00
}
}
public UniTask<T> Task
2020-04-18 04:07:59 +08:00
{
get
{
return new UniTask<T>(this, core.Version);
2020-04-18 04:07:59 +08:00
}
}
public void Reset()
{
handled = false;
core.Reset();
2020-04-18 21:11:40 +08:00
TaskTracker2.TrackActiveTask(this, 2);
2020-04-18 04:07:59 +08:00
}
public void SetResult(T result)
{
2020-04-21 12:36:23 +08:00
core.TrySetResult(result);
2020-04-18 04:07:59 +08:00
}
2020-04-19 01:55:44 +08:00
public void SetCanceled(CancellationToken cancellationToken = default)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
core.TrySetCanceled(cancellationToken);
2020-04-18 04:07:59 +08:00
}
public void SetException(Exception exception)
{
2020-04-21 12:36:23 +08:00
core.TrySetException(exception);
2020-04-18 04:07:59 +08:00
}
public T GetResult(short token)
{
MarkHandled();
return core.GetResult(token);
}
void IUniTaskSource.GetResult(short token)
{
GetResult(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus GetStatus(short token)
2020-04-18 04:07:59 +08:00
{
return core.GetStatus(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus UnsafeGetStatus()
2020-04-18 04:07:59 +08:00
{
return core.UnsafeGetStatus();
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
~UniTaskCompletionSource()
2020-04-18 04:07:59 +08:00
{
// clear error information.
core.Reset();
}
}
public class AutoResetUniTaskCompletionSource<T> : IUniTaskSource<T>, IPromisePoolItem, IPromise<T>
2020-04-18 04:07:59 +08:00
{
static readonly PromisePool<AutoResetUniTaskCompletionSource<T>> pool = new PromisePool<AutoResetUniTaskCompletionSource<T>>();
UniTaskCompletionSourceCore<T> core;
AutoResetUniTaskCompletionSource()
{
}
public static AutoResetUniTaskCompletionSource<T> Create()
{
2020-04-19 01:55:44 +08:00
var result = pool.TryRent() ?? new AutoResetUniTaskCompletionSource<T>();
2020-04-18 21:11:40 +08:00
TaskTracker2.TrackActiveTask(result, 2);
return result;
2020-04-18 04:07:59 +08:00
}
public static AutoResetUniTaskCompletionSource<T> CreateFromCanceled(CancellationToken cancellationToken, out short token)
{
var source = Create();
source.SetCanceled(cancellationToken);
2020-04-18 04:07:59 +08:00
token = source.core.Version;
return source;
}
public static AutoResetUniTaskCompletionSource<T> CreateFromException(Exception exception, out short token)
{
var source = Create();
source.SetException(exception);
token = source.core.Version;
return source;
}
public static AutoResetUniTaskCompletionSource<T> CreateFromResult(T result, out short token)
{
var source = Create();
source.SetResult(result);
token = source.core.Version;
return source;
}
public UniTask<T> Task
2020-04-18 04:07:59 +08:00
{
get
{
return new UniTask<T>(this, core.Version);
2020-04-18 04:07:59 +08:00
}
}
public void SetResult(T result)
{
2020-04-21 12:36:23 +08:00
core.TrySetResult(result);
2020-04-18 04:07:59 +08:00
}
2020-04-19 01:55:44 +08:00
public void SetCanceled(CancellationToken cancellationToken = default)
2020-04-18 04:07:59 +08:00
{
2020-04-21 12:36:23 +08:00
core.TrySetCanceled(cancellationToken);
2020-04-18 04:07:59 +08:00
}
public void SetException(Exception exception)
{
2020-04-21 12:36:23 +08:00
core.TrySetException(exception);
2020-04-18 04:07:59 +08:00
}
public T GetResult(short token)
{
try
{
2020-04-18 21:11:40 +08:00
TaskTracker2.RemoveTracking(this);
2020-04-18 04:07:59 +08:00
return core.GetResult(token);
}
finally
{
pool.TryReturn(this);
}
}
void IUniTaskSource.GetResult(short token)
{
GetResult(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus GetStatus(short token)
2020-04-18 04:07:59 +08:00
{
return core.GetStatus(token);
}
2020-04-20 07:35:06 +08:00
public UniTaskStatus UnsafeGetStatus()
2020-04-18 04:07:59 +08:00
{
return core.UnsafeGetStatus();
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
void IPromisePoolItem.Reset()
{
core.Reset();
}
~AutoResetUniTaskCompletionSource()
{
if (pool.TryReturn(this))
{
GC.ReRegisterForFinalize(this);
}
}
}
2019-05-19 23:14:47 +08:00
}
#endif