SlideShare a Scribd company logo
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 2018
Stuart 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 python
Chetan 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 streams
Bartosz Sypytkowski
 
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
Emertxe Information Technologies Pvt Ltd
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
EPAM
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
Michael Arenzon
 
Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
Sean 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 & Jetpack
Nelson 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 way
Oleg 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 RxJava
Frank Lyaruu
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
Bartosz Sypytkowski
 
Deep Dive into Zone.JS
Deep Dive into Zone.JSDeep Dive into Zone.JS
Deep Dive into Zone.JS
Ilia Idakiev
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
Dmytro Zaitsev
 

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.pptx
River Wang
 
zenject extenject-intro
zenject extenject-introzenject extenject-intro
zenject extenject-intro
River Wang
 
Unity optimize mobile game performance
Unity optimize mobile game performanceUnity optimize mobile game performance
Unity optimize mobile game performance
River 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 model
River 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 Overview
River 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 & Nodes
River 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 Objects
River Wang
 
OpenCascade Technology Overview: Modeling Data
OpenCascade Technology Overview: Modeling DataOpenCascade Technology Overview: Modeling Data
OpenCascade Technology Overview: Modeling Data
River Wang
 
OpenCascade Technology Overview: OCAF
OpenCascade Technology Overview: OCAFOpenCascade Technology Overview: OCAF
OpenCascade Technology Overview: OCAF
River 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: Visualization
River Wang
 
OpenCascade Technology Overview: Foundation Classes
OpenCascade Technology Overview: Foundation ClassesOpenCascade Technology Overview: Foundation Classes
OpenCascade Technology Overview: Foundation Classes
River 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_navigation
River Wang
 
2017 unity5.5 manual_physics
2017 unity5.5 manual_physics2017 unity5.5 manual_physics
2017 unity5.5 manual_physics
River Wang
 
2017 unity5.5 manual_animation
2017 unity5.5 manual_animation2017 unity5.5 manual_animation
2017 unity5.5 manual_animation
River Wang
 
Shader forge設定說明文件
Shader forge設定說明文件Shader forge設定說明文件
Shader forge設定說明文件
River Wang
 
矩陣 轉換
矩陣   轉換矩陣   轉換
矩陣 轉換
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

Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
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
WSO2
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 

Recently uploaded (20)

Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
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
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 

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