SlideShare a Scribd company logo
1 of 14
UniTask
async/await Task in Unity
Introduction
River, 2022/5/29
Why
• Unity 官方不推薦使用 async/await 寫法
• UniTask (用過的都說讚)
• Optimization: for zero GC allocation
• Integrate Coroutine & Unity PlayerLoopTiming
• MonoBehaviour lifecycle cancellation
UniTask<T> / UniTask
• Lightweight alternative of Task<T>, zero allocation and fast excution
for zero overhead async/await integrate with Unity
• .WithCancellation enables Cancel, GetCancellationTokenOnDestroy
synchornizes with lifetime of GameObject
• .ToUniTask accepts progress callback(and all options), Progress.Create
is a lightweight alternative of IProgress<T>
var asset2 = await Resources.LoadAsync<TextAsset>("bar")
.WithCancellation(this.GetCancellationTokenOnDestroy());
var asset3 = await Resources.LoadAsync<TextAsset>("baz")
.ToUniTask(Progress.Create<float>(x => Debug.Log(x)));
• Delay
• Yield
• WaitFor series
await UniTask.DelayFrame(100);
// replacement of yield return new WaitForSeconds/WaitForSecondsRealtime
await UniTask.Delay(TimeSpan.FromSeconds(10), ignoreTimeScale: false);
// (PreUpdate, Update, LateUpdate, etc...)
await UniTask.Yield(PlayerLoopTiming.PreLateUpdate);
// replacement of yield return null
await UniTask.Yield();
await UniTask.NextFrame();
await UniTask.WaitForEndOfFrame(this); // this is MonoBehaviour
await UniTask.WaitForFixedUpdate();
await UniTask.WaitUntil(() => isActive == false);
await UniTask.WaitUntilValueChanged(this, x => x.isActive);
• Coroutine & Task
• Switch Thread
• WhenAll
// You can await IEnumerator coroutines
await FooCoroutineEnumerator();
// You can await a standard task
await Task.Run(() => 100);
// Multithreading, run on ThreadPool under this code
await UniTask.SwitchToThreadPool();
/* work on ThreadPool */
// return to MainThread
await UniTask.SwitchToMainThread();
/* work on main thread */
// concurrent async-wait and get results easily by tuple syntax
var (google, bing, yahoo) = await UniTask.WhenAll(task1, task2, task3);
// shorthand of WhenAll, tuple can await directly
var (google2, bing2, yahoo2) = await (task1, task2, task3);
• Timeout
• TimeoutController (optimized)
var cts = new CancellationTokenSource();
cts.CancelAfterSlim(TimeSpan.FromSeconds(5)); // 5sec timeout.
try
{
await UnityWebRequest.Get("http://foo").SendWebRequest().WithCancellation(cts.Token);
}
catch (OperationCanceledException ex)
{
if (ex.CancellationToken == cts.Token) { ... } // 5sec timeout
}
TimeoutController timeoutController = new TimeoutController(); // setup to field for reuse.
async UniTask FooAsync()
{
try
{
// you can pass timeoutController.Timeout(TimeSpan) to cancellationToken.
await UnityWebRequest.Get("http://foo").SendWebRequest()
.WithCancellation(timeoutController.Timeout(TimeSpan.FromSeconds(5)));
timeoutController.Reset(); // call Reset(Stop timeout timer and ready for reuse) when succeed.
}
catch (OperationCanceledException ex)
{
if (timeoutController.IsTimeout()) { ... } // timeout
}
}
• Progress (.Create(), IProgress<>)
• Better than System.Progress
var progress = Progress.Create<float>(x => Debug.Log(x));
var request = await UnityWebRequest.Get("http://google.co.jp").SendWebRequest()
.ToUniTask(progress: progress);
public class Foo : MonoBehaviour, IProgress<float>
{
public void Report(float value)
{
UnityEngine.Debug.Log(value);
}
public async UniTaskVoid WebRequest()
{
var request = await UnityWebRequest.Get("http://google.co.jp").SendWebRequest()
.ToUniTask(progress: this); // pass this
}
}
• PlayerLoop - UniTask run on a custom PlayerLoop
• PlayerLoopTiming
• Initialization = 0,
• LastInitialization = 1,
• EarlyUpdate = 2,
• LastEarlyUpdate = 3,
• FixedUpdate = 4,
• LastFixedUpdate = 5,
• PreUpdate = 6,
• LastPreUpdate = 7,
• Update = 8,
• LastUpdate = 9,
• PreLateUpdate = 10,
• LastPreLateUpdate = 11,
• PostLateUpdate = 12,
• LastPostLateUpdate = 13
• TimeUpdate = 14,
• LastTimeUpdate = 15,
async void vs async UniTaskVoid
• async void – not run on UniTask systems. 不建議使用
• async UniTaskVoid 建議使用
• Lightweight of async UniTask
• No awaitable completion (fire and forgot)
• Report error/exception immediately to UniTaskSchedular.UnobservedTaskException
• Async lambda (for event) 建議使用 UniTask.Action / UniTask.UnityAction
// Bad: async void
actEvent += async () => { }; unityEvent += async () => { };
// Ok: create Action delegate by lambda
actEvent += UniTask.Action(async () => { await UniTask.Yield(); });
unityEvent += UniTask.UnityAction(async () => { await UniTask.Yield(); });
async UniTaskVoid Start() { ... }
第三方/插件整合
• TextMeshPro
• Addressables
• DOTween
AsyncEnumerable and Async LINQ
• UniTaskAsyncEnumerable implements asynchronous LINQ, similar to
LINQ in IEnumerable<T> or Rx in IObservable<T>. All standard LINQ
query operators can be applied to asynchronous streams.
Awaitable Events
• All UGUI implements ***AsAsyncEnumerable
• All MonoBehaviour message events can convert async-streams
• AsyncReactiveProperty, AsyncReadOnlyReactiveProperty
• ReactiveProperty.
• BindTo extension method: binding asynchronous stream values to Unity
components(Text/Selectable/TMP/Text).
var rp = new AsyncReactiveProperty<int>(99);
// AsyncReactiveProperty itself is IUniTaskAsyncEnumerable, you can query by LINQ
rp.ForEachAsync(x => { Debug.Log(x); },
this.GetCancellationTokenOnDestroy())
.Forget();
rp.Value = 10; // push 10 to all subscriber
rp.Value = 11; // push 11 to all subscriber
// WithoutCurrent ignore initial value; BindTo bind stream value to unity components.
rp.WithoutCurrent().BindTo(this.textComponent);
await rp.WaitAsync(); // wait until next value set
Channel
• 取代 System.Threading.Tasks.Channels,類似 GoLang Channel
• Currently it only supports multiple-producer, single-consumer
unbounded channels.
• For producer(.Writer), use TryWrite to push value and TryComplete to
complete channel.
• For consumer(.Reader), use TryRead, WaitToReadAsync, ReadAsync,
Completion and ReadAllAsync to read queued messages

More Related Content

Similar to 20220529_UniTask_Intro.pptx

CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitSpiffy
 
Azure Durable Funkiness - .NET Oxford June 2018
Azure Durable Funkiness - .NET Oxford June 2018Azure Durable Funkiness - .NET Oxford June 2018
Azure Durable Funkiness - .NET Oxford June 2018Stuart Leeks
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研vorfeed chen
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Fwdays
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETEPAM
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingMichael Arenzon
 
Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - CoroutineSean Tsai
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackNelson Glauber Leal
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
 
Deep Dive into Zone.JS
Deep Dive into Zone.JSDeep Dive into Zone.JS
Deep Dive into Zone.JSIlia Idakiev
 

Similar to 20220529_UniTask_Intro.pptx (20)

CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
 
Azure Durable Funkiness - .NET Oxford June 2018
Azure Durable Funkiness - .NET Oxford June 2018Azure Durable Funkiness - .NET Oxford June 2018
Azure Durable Funkiness - .NET Oxford June 2018
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
Deep Dive into Zone.JS
Deep Dive into Zone.JSDeep Dive into Zone.JS
Deep Dive into Zone.JS
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 

More from River Wang

FairyGUISDK_UIPackage_Analysis.pptx
FairyGUISDK_UIPackage_Analysis.pptxFairyGUISDK_UIPackage_Analysis.pptx
FairyGUISDK_UIPackage_Analysis.pptxRiver Wang
 
zenject extenject-intro
zenject extenject-introzenject extenject-intro
zenject extenject-introRiver Wang
 
Unity optimize mobile game performance
Unity optimize mobile game performanceUnity optimize mobile game performance
Unity optimize mobile game performanceRiver Wang
 
DoozyUI_基礎介紹教學
DoozyUI_基礎介紹教學DoozyUI_基礎介紹教學
DoozyUI_基礎介紹教學River Wang
 
Gamedev: Multi-threaded animate model
Gamedev: Multi-threaded animate modelGamedev: Multi-threaded animate model
Gamedev: Multi-threaded animate modelRiver Wang
 
桌面應用工具軟體開發方案評估 (Based on Unity engine)
桌面應用工具軟體開發方案評估 (Based on Unity engine)桌面應用工具軟體開發方案評估 (Based on Unity engine)
桌面應用工具軟體開發方案評估 (Based on Unity engine)River Wang
 
OGRE v2.1 manual - Technical Overview
OGRE v2.1 manual - Technical OverviewOGRE v2.1 manual - Technical Overview
OGRE v2.1 manual - Technical OverviewRiver Wang
 
OGRE v2.1 manual - Changes: Objects, Scene & Nodes
OGRE v2.1 manual - Changes: Objects, Scene & NodesOGRE v2.1 manual - Changes: Objects, Scene & Nodes
OGRE v2.1 manual - Changes: Objects, Scene & NodesRiver Wang
 
OGRE v1.10 manual - The Core Objects
OGRE v1.10 manual - The Core ObjectsOGRE v1.10 manual - The Core Objects
OGRE v1.10 manual - The Core ObjectsRiver Wang
 
OpenCascade Technology Overview: Modeling Data
OpenCascade Technology Overview: Modeling DataOpenCascade Technology Overview: Modeling Data
OpenCascade Technology Overview: Modeling DataRiver Wang
 
OpenCascade Technology Overview: OCAF
OpenCascade Technology Overview: OCAFOpenCascade Technology Overview: OCAF
OpenCascade Technology Overview: OCAFRiver Wang
 
[breakdown] Shadow of the Colossus. (Chinese translation中譯)
[breakdown] Shadow of the Colossus. (Chinese translation中譯)[breakdown] Shadow of the Colossus. (Chinese translation中譯)
[breakdown] Shadow of the Colossus. (Chinese translation中譯)River Wang
 
OpenCascade Technology Overview: Visualization
OpenCascade Technology Overview: VisualizationOpenCascade Technology Overview: Visualization
OpenCascade Technology Overview: VisualizationRiver Wang
 
OpenCascade Technology Overview: Foundation Classes
OpenCascade Technology Overview: Foundation ClassesOpenCascade Technology Overview: Foundation Classes
OpenCascade Technology Overview: Foundation ClassesRiver Wang
 
2017 graphics-01: 電腦圖學繪圖流程
2017 graphics-01: 電腦圖學繪圖流程2017 graphics-01: 電腦圖學繪圖流程
2017 graphics-01: 電腦圖學繪圖流程River Wang
 
2017 unity5.5 manual_navigation
2017 unity5.5 manual_navigation2017 unity5.5 manual_navigation
2017 unity5.5 manual_navigationRiver Wang
 
2017 unity5.5 manual_physics
2017 unity5.5 manual_physics2017 unity5.5 manual_physics
2017 unity5.5 manual_physicsRiver Wang
 
2017 unity5.5 manual_animation
2017 unity5.5 manual_animation2017 unity5.5 manual_animation
2017 unity5.5 manual_animationRiver Wang
 
Shader forge設定說明文件
Shader forge設定說明文件Shader forge設定說明文件
Shader forge設定說明文件River Wang
 

More from River Wang (20)

FairyGUISDK_UIPackage_Analysis.pptx
FairyGUISDK_UIPackage_Analysis.pptxFairyGUISDK_UIPackage_Analysis.pptx
FairyGUISDK_UIPackage_Analysis.pptx
 
zenject extenject-intro
zenject extenject-introzenject extenject-intro
zenject extenject-intro
 
Unity optimize mobile game performance
Unity optimize mobile game performanceUnity optimize mobile game performance
Unity optimize mobile game performance
 
DoozyUI_基礎介紹教學
DoozyUI_基礎介紹教學DoozyUI_基礎介紹教學
DoozyUI_基礎介紹教學
 
Gamedev: Multi-threaded animate model
Gamedev: Multi-threaded animate modelGamedev: Multi-threaded animate model
Gamedev: Multi-threaded animate model
 
桌面應用工具軟體開發方案評估 (Based on Unity engine)
桌面應用工具軟體開發方案評估 (Based on Unity engine)桌面應用工具軟體開發方案評估 (Based on Unity engine)
桌面應用工具軟體開發方案評估 (Based on Unity engine)
 
OGRE v2.1 manual - Technical Overview
OGRE v2.1 manual - Technical OverviewOGRE v2.1 manual - Technical Overview
OGRE v2.1 manual - Technical Overview
 
OGRE v2.1 manual - Changes: Objects, Scene & Nodes
OGRE v2.1 manual - Changes: Objects, Scene & NodesOGRE v2.1 manual - Changes: Objects, Scene & Nodes
OGRE v2.1 manual - Changes: Objects, Scene & Nodes
 
OGRE v1.10 manual - The Core Objects
OGRE v1.10 manual - The Core ObjectsOGRE v1.10 manual - The Core Objects
OGRE v1.10 manual - The Core Objects
 
OpenCascade Technology Overview: Modeling Data
OpenCascade Technology Overview: Modeling DataOpenCascade Technology Overview: Modeling Data
OpenCascade Technology Overview: Modeling Data
 
OpenCascade Technology Overview: OCAF
OpenCascade Technology Overview: OCAFOpenCascade Technology Overview: OCAF
OpenCascade Technology Overview: OCAF
 
[breakdown] Shadow of the Colossus. (Chinese translation中譯)
[breakdown] Shadow of the Colossus. (Chinese translation中譯)[breakdown] Shadow of the Colossus. (Chinese translation中譯)
[breakdown] Shadow of the Colossus. (Chinese translation中譯)
 
OpenCascade Technology Overview: Visualization
OpenCascade Technology Overview: VisualizationOpenCascade Technology Overview: Visualization
OpenCascade Technology Overview: Visualization
 
OpenCascade Technology Overview: Foundation Classes
OpenCascade Technology Overview: Foundation ClassesOpenCascade Technology Overview: Foundation Classes
OpenCascade Technology Overview: Foundation Classes
 
2017 graphics-01: 電腦圖學繪圖流程
2017 graphics-01: 電腦圖學繪圖流程2017 graphics-01: 電腦圖學繪圖流程
2017 graphics-01: 電腦圖學繪圖流程
 
2017 unity5.5 manual_navigation
2017 unity5.5 manual_navigation2017 unity5.5 manual_navigation
2017 unity5.5 manual_navigation
 
2017 unity5.5 manual_physics
2017 unity5.5 manual_physics2017 unity5.5 manual_physics
2017 unity5.5 manual_physics
 
2017 unity5.5 manual_animation
2017 unity5.5 manual_animation2017 unity5.5 manual_animation
2017 unity5.5 manual_animation
 
Shader forge設定說明文件
Shader forge設定說明文件Shader forge設定說明文件
Shader forge設定說明文件
 
矩陣 轉換
矩陣   轉換矩陣   轉換
矩陣 轉換
 

Recently uploaded

%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 

Recently uploaded (20)

%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 

20220529_UniTask_Intro.pptx

  • 1. UniTask async/await Task in Unity Introduction River, 2022/5/29
  • 2. Why • Unity 官方不推薦使用 async/await 寫法 • UniTask (用過的都說讚) • Optimization: for zero GC allocation • Integrate Coroutine & Unity PlayerLoopTiming • MonoBehaviour lifecycle cancellation
  • 3. UniTask<T> / UniTask • Lightweight alternative of Task<T>, zero allocation and fast excution for zero overhead async/await integrate with Unity • .WithCancellation enables Cancel, GetCancellationTokenOnDestroy synchornizes with lifetime of GameObject • .ToUniTask accepts progress callback(and all options), Progress.Create is a lightweight alternative of IProgress<T> var asset2 = await Resources.LoadAsync<TextAsset>("bar") .WithCancellation(this.GetCancellationTokenOnDestroy()); var asset3 = await Resources.LoadAsync<TextAsset>("baz") .ToUniTask(Progress.Create<float>(x => Debug.Log(x)));
  • 4. • Delay • Yield • WaitFor series await UniTask.DelayFrame(100); // replacement of yield return new WaitForSeconds/WaitForSecondsRealtime await UniTask.Delay(TimeSpan.FromSeconds(10), ignoreTimeScale: false); // (PreUpdate, Update, LateUpdate, etc...) await UniTask.Yield(PlayerLoopTiming.PreLateUpdate); // replacement of yield return null await UniTask.Yield(); await UniTask.NextFrame(); await UniTask.WaitForEndOfFrame(this); // this is MonoBehaviour await UniTask.WaitForFixedUpdate(); await UniTask.WaitUntil(() => isActive == false); await UniTask.WaitUntilValueChanged(this, x => x.isActive);
  • 5. • Coroutine & Task • Switch Thread • WhenAll // You can await IEnumerator coroutines await FooCoroutineEnumerator(); // You can await a standard task await Task.Run(() => 100); // Multithreading, run on ThreadPool under this code await UniTask.SwitchToThreadPool(); /* work on ThreadPool */ // return to MainThread await UniTask.SwitchToMainThread(); /* work on main thread */ // concurrent async-wait and get results easily by tuple syntax var (google, bing, yahoo) = await UniTask.WhenAll(task1, task2, task3); // shorthand of WhenAll, tuple can await directly var (google2, bing2, yahoo2) = await (task1, task2, task3);
  • 6. • Timeout • TimeoutController (optimized) var cts = new CancellationTokenSource(); cts.CancelAfterSlim(TimeSpan.FromSeconds(5)); // 5sec timeout. try { await UnityWebRequest.Get("http://foo").SendWebRequest().WithCancellation(cts.Token); } catch (OperationCanceledException ex) { if (ex.CancellationToken == cts.Token) { ... } // 5sec timeout } TimeoutController timeoutController = new TimeoutController(); // setup to field for reuse. async UniTask FooAsync() { try { // you can pass timeoutController.Timeout(TimeSpan) to cancellationToken. await UnityWebRequest.Get("http://foo").SendWebRequest() .WithCancellation(timeoutController.Timeout(TimeSpan.FromSeconds(5))); timeoutController.Reset(); // call Reset(Stop timeout timer and ready for reuse) when succeed. } catch (OperationCanceledException ex) { if (timeoutController.IsTimeout()) { ... } // timeout } }
  • 7. • Progress (.Create(), IProgress<>) • Better than System.Progress var progress = Progress.Create<float>(x => Debug.Log(x)); var request = await UnityWebRequest.Get("http://google.co.jp").SendWebRequest() .ToUniTask(progress: progress); public class Foo : MonoBehaviour, IProgress<float> { public void Report(float value) { UnityEngine.Debug.Log(value); } public async UniTaskVoid WebRequest() { var request = await UnityWebRequest.Get("http://google.co.jp").SendWebRequest() .ToUniTask(progress: this); // pass this } }
  • 8. • PlayerLoop - UniTask run on a custom PlayerLoop • PlayerLoopTiming • Initialization = 0, • LastInitialization = 1, • EarlyUpdate = 2, • LastEarlyUpdate = 3, • FixedUpdate = 4, • LastFixedUpdate = 5, • PreUpdate = 6, • LastPreUpdate = 7, • Update = 8, • LastUpdate = 9, • PreLateUpdate = 10, • LastPreLateUpdate = 11, • PostLateUpdate = 12, • LastPostLateUpdate = 13 • TimeUpdate = 14, • LastTimeUpdate = 15,
  • 9. async void vs async UniTaskVoid • async void – not run on UniTask systems. 不建議使用 • async UniTaskVoid 建議使用 • Lightweight of async UniTask • No awaitable completion (fire and forgot) • Report error/exception immediately to UniTaskSchedular.UnobservedTaskException • Async lambda (for event) 建議使用 UniTask.Action / UniTask.UnityAction // Bad: async void actEvent += async () => { }; unityEvent += async () => { }; // Ok: create Action delegate by lambda actEvent += UniTask.Action(async () => { await UniTask.Yield(); }); unityEvent += UniTask.UnityAction(async () => { await UniTask.Yield(); }); async UniTaskVoid Start() { ... }
  • 11. AsyncEnumerable and Async LINQ • UniTaskAsyncEnumerable implements asynchronous LINQ, similar to LINQ in IEnumerable<T> or Rx in IObservable<T>. All standard LINQ query operators can be applied to asynchronous streams.
  • 12. Awaitable Events • All UGUI implements ***AsAsyncEnumerable • All MonoBehaviour message events can convert async-streams
  • 13. • AsyncReactiveProperty, AsyncReadOnlyReactiveProperty • ReactiveProperty. • BindTo extension method: binding asynchronous stream values to Unity components(Text/Selectable/TMP/Text). var rp = new AsyncReactiveProperty<int>(99); // AsyncReactiveProperty itself is IUniTaskAsyncEnumerable, you can query by LINQ rp.ForEachAsync(x => { Debug.Log(x); }, this.GetCancellationTokenOnDestroy()) .Forget(); rp.Value = 10; // push 10 to all subscriber rp.Value = 11; // push 11 to all subscriber // WithoutCurrent ignore initial value; BindTo bind stream value to unity components. rp.WithoutCurrent().BindTo(this.textComponent); await rp.WaitAsync(); // wait until next value set
  • 14. Channel • 取代 System.Threading.Tasks.Channels,類似 GoLang Channel • Currently it only supports multiple-producer, single-consumer unbounded channels. • For producer(.Writer), use TryWrite to push value and TryComplete to complete channel. • For consumer(.Reader), use TryRead, WaitToReadAsync, ReadAsync, Completion and ReadAllAsync to read queued messages