대기 중인 코드 예제 참조
대기 가능한 코드 예시를 참조하여 일반적인 비동기 프로그래밍 문제를 해결합니다.
읽는 시간 3분최근 업데이트: 9일 전
이 참조의 예제는 비동기 코드를 작성할 때 발생하는 일반적인 시나리오에 대한 솔루션을 보여줍니다.
Awaitable비동기 테스트
Unity의 Test Framework에서는 를 유효한 테스트 반환 유형으로 인식하지 않습니다. 그러나 다음 예제는 의 구현을 사용하여 비동기 테스트를 작성하는 방법을 보여줍니다.
AwaitableIEnumeratorAwaitable[UnityTest]public IEnumerator SomeAsyncTest(){ async Awaitable TestImplementation(){ // test something with async / await support here }; return TestImplementation();}
프레임 코루틴
Awaitableasync Awaitable SampleSchedulingJobsForNextFrame(){ // Wait until end of frame to avoid competing over resources with other Unity subsystems await Awaitable.EndOfFrameAsync(); var jobHandle = ScheduleSomethingWithJobSystem(); // Let the job execute while the next frame starts await Awaitable.NextFrameAsync(); jobHandle.Complete(); // Use results of computation}JobHandle ScheduleSomethingWithJobSystem(){ ...}
조건부 대기
반복기 기반 코루틴에서 WaitUntil은 델리게이트가 를 평가할 때까지 코루틴 실행을 일시 중지합니다. 취소 토큰을 사용하여 조건이 변경될 때까지 기다리도록 하여 반환 비동기 메서드에 대해 동등한 동작을 만들 수 있습니다.
trueAwaitablepublic static async Awaitable AwaitableUntil(Func<bool> condition, CancellationToken cancellationToken){ while(!condition()){ cancellationToken.ThrowIfCancellationRequested(); await Awaitable.NextFrameAsync(); }}
그런 다음 다음과 같이 취소 토큰을 전달할 수 있습니다.
cancellationTokenSource = new CancellationTokenSource();currentTask = AwaitableUntil(myCondition, cancellationTokenSource.Token);
비동기식으로 리소스 로드
메인 스레드를 차단하지 않도록 비동기 리소스 로딩 작업을 할 수 있습니다.
awaitpublic async Awaitable LoadResourcesAsync(){ // Load texture resource asynchronously var operation = Resources.LoadAsync("my-texture"); // Return control to the main thread while the resource loads 대기 작업; var texture = operation.asset as Texture2D;}
합성
동일한 방법으로 여러 개의 다른 호환 타입을 할 수 있습니다.
awaitawaitpublic async Awaitable Bar(){ await CallSomeThirdPartyAPIReturningDotnetTask(); await Awaitable.NextFrameAsync(); await SceneManager.LoadSceneAsync("my-scene"); await SomeUserCodeReturningAwaitable(); ...}
.NET Task에서 대기 가능 래핑
AwaitableTaskTaskWhenAllWhenAnyAsTask// Implement custom AsTask extension methods to wrap Awaitable in Taskpublic static class AwaitableExtensions { public static async Task AsTask(this Awaitable a) { a;를 기다립니다. } public static async Task<T> AsTask<T>(this Awaitable<T> a) { return await a; } }
여러 번 결과를 기다립니다.
AwaitableTaskAwaitableAwaitableawaitAwaitable안전하지 않은 버전
다음 코드는 안전하지 않으며 예외와 망가진 현상을 리드합니다.
async Awaitable Bar(){ var taskWithResult = SomeAwaitableReturningFunction(); var awaitOnce = await taskWithResult; // Do something // The following will cause errors because at this point taskWithResult has already been pooled back var awaitTwice = await taskWithResult; }
안전한 버전
이는 할당 비용으로 Awaitable을 작업에 래핑할 수 있는 시나리오 중 하나입니다. 그런 다음 는 여러 번 안전하게 기다릴 수 있습니다.
Task// Implement custom AsTask extension methods to wrap Awaitable in Taskpublic static class AwaitableExtensions { public static async Task AsTask(this Awaitable a) { a;를 기다립니다. } public static async Task<T> AsTask<T>(this Awaitable<T> a) { return await a; } }async Awaitable Bar(){ var taskWithResult = SomeAwaitableReturningFunction(); // Wrap the returned Awaitable in a Task var taskWithResultAsTask = taskWithResult.AsTask(); // The task can now be safely awaited multiple times, at the cost of allocating var awaitOnce = await taskWithResultAsTask; // Do something var awaitTwice = await taskWithResultAsTask; }