public static Task AsTask(this UniTask task) { try { UniTask.Awaiter awaiter; try { awaiter = task.GetAwaiter(); } catch (Exception ex) { return(Task.FromException(ex)); } if (awaiter.IsCompleted) { try { awaiter.GetResult(); // check token valid on Succeeded return(Task.CompletedTask); } catch (Exception ex) { return(Task.FromException(ex)); } } var tcs = new TaskCompletionSource <object>(); awaiter.SourceOnCompleted(state => { using (var tuple = (StateTuple <TaskCompletionSource <object>, UniTask.Awaiter>)state) { var(inTcs, inAwaiter) = tuple; try { inAwaiter.GetResult(); inTcs.SetResult(null); } catch (Exception ex) { inTcs.SetException(ex); } } }, StateTuple.Create(tcs, awaiter)); return(tcs.Task); } catch (Exception ex) { return(Task.FromException(ex)); } }
public static Task <T> AsTask <T>(this UniTask <T> task) { try { UniTask <T> .Awaiter awaiter; try { awaiter = task.GetAwaiter(); } catch (Exception ex) { return(Task.FromException <T>(ex)); } if (awaiter.IsCompleted) { try { var result = awaiter.GetResult(); return(Task.FromResult(result)); } catch (Exception ex) { return(Task.FromException <T>(ex)); } } var tcs = new TaskCompletionSource <T>(); awaiter.SourceOnCompleted(state => { using (var tuple = (StateTuple <TaskCompletionSource <T>, UniTask <T> .Awaiter>)state) { var(inTcs, inAwaiter) = tuple; try { var result = inAwaiter.GetResult(); inTcs.SetResult(result); } catch (Exception ex) { inTcs.SetException(ex); } } }, StateTuple.Create(tcs, awaiter)); return(tcs.Task); } catch (Exception ex) { return(Task.FromException <T>(ex)); } }
UniTaskCompletionSourceCore <T[]> core; // don't reset(called after GetResult, will invoke TrySetException.) public WhenAllPromise(UniTask <T>[] tasks, int tasksLength) { TaskTracker.TrackActiveTask(this, 3); this.completeCount = 0; if (tasksLength == 0) { this.result = Array.Empty <T>(); core.TrySetResult(result); return; } this.result = new T[tasksLength]; for (int i = 0; i < tasksLength; i++) { UniTask <T> .Awaiter awaiter; try { awaiter = tasks[i].GetAwaiter(); } catch (Exception ex) { core.TrySetException(ex); continue; } if (awaiter.IsCompleted) { TryInvokeContinuation(this, awaiter, i); } else { awaiter.SourceOnCompleted(state => { using (var t = (StateTuple <WhenAllPromise <T>, UniTask <T> .Awaiter, int>)state) { TryInvokeContinuation(t.Item1, t.Item2, t.Item3); } }, StateTuple.Create(this, awaiter, i)); } } }