기술 자료

Unity 엔진

Unity 엔진

대기 중인 코드 예제 참조

대기 가능한 코드 예시를 참조하여 일반적인 비동기 프로그래밍 문제를 해결합니다.
읽는 시간 3분최근 업데이트: 9일 전

이 참조의 예제는 비동기 코드를 작성할 때 발생하는 일반적인 시나리오에 대한
Awaitable
솔루션을 보여줍니다.

비동기 테스트

Unity의 Test Framework에서는
Awaitable
를 유효한 테스트 반환 유형으로 인식하지 않습니다. 그러나 다음 예제는
IEnumerator
의
Awaitable
구현을 사용하여 비동기 테스트를 작성하는 방법을 보여줍니다.
[UnityTest]public IEnumerator SomeAsyncTest(){ async Awaitable TestImplementation(){ // test something with async / await support here }; return TestImplementation();}

프레임 코루틴

Awaitable
클래스에서 프레임 관련 비동기 메서드를 사용하여 반복기 기반 코루틴 대신 비동기 Unity 코루틴을 생성할 수 있습니다.
async 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은 델리게이트가
true
를 평가할 때까지 코루틴 실행을 일시 중지합니다. 취소 토큰을 사용하여 조건이 변경될 때까지 기다리도록 하여
Awaitable
반환 비동기 메서드에 대해 동등한 동작을 만들 수 있습니다.
public static async Awaitable AwaitableUntil(Func<bool> condition, CancellationToken cancellationToken){ while(!condition()){ cancellationToken.ThrowIfCancellationRequested(); await Awaitable.NextFrameAsync(); }}
그런 다음 다음과 같이 취소 토큰을 전달할 수 있습니다.
cancellationTokenSource = new CancellationTokenSource();currentTask = AwaitableUntil(myCondition, cancellationTokenSource.Token);

비동기식으로 리소스 로드

메인 스레드를 차단하지 않도록 비동기 리소스 로딩 작업을
await
할 수 있습니다.
public 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;}

합성

동일한 방법으로 여러 개의 다른
await
호환 타입을
await
할 수 있습니다.
public async Awaitable Bar(){ await CallSomeThirdPartyAPIReturningDotnetTask(); await Awaitable.NextFrameAsync(); await SceneManager.LoadSceneAsync("my-scene"); await SomeUserCodeReturningAwaitable(); ...}

.NET Task에서 대기 가능 래핑

Awaitable
의 한계를 해결하려면 .NET
Task
에 래핑할 수 있습니다. 이렇게 하면 할당 비용이 발생하지만
Task
API에서
WhenAll
및
WhenAny
와 같은 메서드에 액세스할 수 있습니다. 이를 위해 다음과 같이 사용자 지정
AsTask
확장 방법을 작성할 수 있습니다.
// 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; } }

여러 번 결과를 기다립니다.

Awaitable
와
Task
의 주요 차이점은 할당을 줄이기 위해
Awaitable
객체를 풀링하는 것입니다. 결과를 여러 번 완료하는
Awaitable
반환 메서드를 안전하게
await
할 수는 없습니다. 원본
Awaitable
오브젝트가 반환되면 풀에 반환됩니다.

안전하지 않은 버전

다음 코드는 안전하지 않으며 예외와 망가진 현상을 리드합니다.
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; }

추가 리소스