From 213915b06d5cb94f672bd22068d482dad8cb85a6 Mon Sep 17 00:00:00 2001 From: SeongChan Lee Date: Thu, 6 Oct 2022 12:04:59 +0900 Subject: [PATCH] Detach continuations of AsyncOperationHandle from the Completed callback --- .../AddressablesAsyncExtensions.cs | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/UniTask/Assets/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs b/src/UniTask/Assets/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs index f321bdb..80bd0f9 100644 --- a/src/UniTask/Assets/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs +++ b/src/UniTask/Assets/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs @@ -44,7 +44,21 @@ namespace Cysharp.Threading.Tasks return UniTask.CompletedTask; } - return new UniTask(AsyncOperationHandleConfiguredSource.Create(handle, timing, progress, cancellationToken, out var token), token); + var task = new UniTask(AsyncOperationHandleConfiguredSource.Create(handle, timing, progress, cancellationToken, out var token), token); + return DetachContinuationFromAsyncOperationHandleCompletedCallback(task); + } + + private static async UniTask DetachContinuationFromAsyncOperationHandleCompletedCallback(UniTask task) + { + try + { + await task; + } + finally + { + // Completed callback is deferred until the LateUpdate of the current frame, + await UniTask.Yield(PlayerLoopTiming.PostLateUpdate); + } } public struct AsyncOperationHandleAwaiter : ICriticalNotifyCompletion @@ -255,7 +269,21 @@ namespace Cysharp.Threading.Tasks return UniTask.FromResult(handle.Result); } - return new UniTask(AsyncOperationHandleConfiguredSource.Create(handle, timing, progress, cancellationToken, out var token), token); + var task = new UniTask(AsyncOperationHandleConfiguredSource.Create(handle, timing, progress, cancellationToken, out var token), token); + return DetachContinuationFromAsyncOperationHandleCompletedCallback(task); + } + + private static async UniTask DetachContinuationFromAsyncOperationHandleCompletedCallback(UniTask task) + { + try + { + return await task; + } + finally + { + // Completed callback is deferred until the LateUpdate of the current frame, + await UniTask.Yield(PlayerLoopTiming.PostLateUpdate); + } } sealed class AsyncOperationHandleConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> @@ -398,4 +426,4 @@ namespace Cysharp.Threading.Tasks } } -#endif \ No newline at end of file +#endif