race 표현식을 사용하여 블록 내 둘 이상의 비동기화 표현식을 동시에 실행할 수 있습니다. 가장 빠른 표현식이 완료되면, 해당 표현식이 ‘경합에서 승리’합니다. '패배'하는 나머지 표현식은 취소되며 그다음 race 이후의 표현식이 평가됩니다.
set WinnerResult = race:
# All three async functions start at the same time
AsyncFunctionLongTime()
AsyncFunctionShortTime() # This will win and its result is used
AsyncFunctionMediumTime()
# Next expression is called after the fastest async function completes
# / when the fastest/shortest async function task (AsyncFunctionShortTime()) completes
# and all other async function tasks (AsyncFunctionLongTime(), AsyncFunctionMediumTime()) are canceled.
NextExpression(WinnerResult)다음 코드는 race 표현식의 구문입니다.
expression0
race:
slow-expression
mid-expression
fast-expression
expression1아래 다이어그램은 표현식의 실행 플로입니다.
race 표현식의 사용
| |
| 비동기 |
|
|
|
|
| 코드 블록 내에서 '승리'하는 표현식이 완료되면 |
|
|
|
|
단순해 보일 수 있으나 race는 Verse에서 사용할 수 있는 가장 유용하고 강력한 표현식 중 하나입니다. 기타 복잡한 비동기화 코드를 중단하고 일찍 탈출할 수 있는 체계적인 방법이기 때문입니다. 중단하고자 하는 코드를 언제 중단해야 하는지 결정하는 데 필요한 모든 테스트를 코드와 별개로 저장하고 있어서 이 작업은 아주 깔끔하게 처리됩니다.
일정 시간이 지나거나 어떤 복잡한 이벤트 시퀀스가 트리거된 후에 복잡한 행동을 중단해야 할 필요가 있나요? race가 없다면 일반적으로 복잡한 행동을 전부 폴링하는 등의 여러 테스트를 진행해야 합니다. race가 있으므로 표현식을 중단할 모든 조건을 복잡한 행동과 나란히 서브표현식으로 추가하기만 하면 됩니다.
race:
ComplexBehavior() # Could be simple or as complex as a whole game
Sleep(60.0) # Timeout after one minute
EventTrigger() # Some other arbitrary test that can be used to stoprace의 결과를 통해 어떤 서브표현식이 가장 먼저 완료되어 경합에서 승리했는지 알 수 있습니다.
# Adding a unique result to subexpressions so it can
# be used to determine which subexpression won
Winner := race:
block: # task 1
AsyncFunction1()
1
block: # task 2
AsyncFunction2a()
AsyncFunction2b()
AsyncFunction2c()