본문 바로가기
개발/Unity

Unity) 비동기 프로그래밍(Aync, Await)

by 테샤르 2020. 12. 7.

비동기 프로그래밍(Aync, Await)

I / O 요구가 있는 상황(파일을 읽거나, 데이터베이스 액세스, 네트워크 요청, 응답 등등)에서는 비동기 프로그래밍을 활용하는 것이 좋다. C#에서는 언어  수준에서 지원하기 때문에 쉽게 사용이 가능하다. TAP(Task-base Asynchronous Pattern)이라고 하는 방식을 따른다.

동기식 (30분) 비동기식(15분)

 

다음은 게임에서 데이터를 계산하는 과정에서 예시는 다음과 같다.

CalculateButton을 클릭하는 동안에는 제어권 넘겨주고 계산을 처리하고 다시 UI에 표현하는 예시이다.

private DamageResult CalculateDamageDone()
{
    // Code omitted:
    //
    // Does an expensive calculation and returns
    // the result of that calculation.
}

calculateButton.Clicked += async (o, e) =>
{
    // This line will yield control to the UI while CalculateDamageDone()
    // performs its work. The UI thread is free to perform other work.
    var damageResult = await Task.Run(() => CalculateDamageDone());
    DisplayDamage(damageResult);
};
반응형

함수로 구현하면 다음과 같다.

    async void Start()
    {
        var resultFlag = await Init();
    }


    public async Task<bool> Init(){

        return true;
    }

기본적으로 비동기 메소드에서만 처리가 된다. Task가 완료될 때까지 교착상태가 발생하기 때문에 충분히 고려하고 사용해야 한다. 테스트이기 때문에 생성한 오브젝트가 파괴되더라고 실행된다.

 

프리 팹을 불러오는 과정을 구현하면 다음과 같다.

public IEnumerator LoadPrefab(Action<GameObject> callback)
{
    if (!assetIsLoaded)
    {
        yield return LoadPrefabIntoCache();
    }
    
    var prefab = GetPrefabFromCache();
    callback(prefab);
}

// Some code that wants to use the coroutine;
GameObject prefab = null;
yield return LoadPrefab(result => { prefab = result; });

 

 

참고 URL : [ Mircosoft C# Async ]

 

C#의 비동기 프로그래밍

async, await 및 Task를 사용하여 비동기 프로그래밍을 지원하는 C# 언어에 대해 간략히 설명합니다.

docs.microsoft.com

 

 ★

 

반응형

댓글