{"id":13663371,"url":"https://github.com/Cysharp/UniTask","last_synced_at":"2025-04-25T13:33:07.349Z","repository":{"id":37663111,"uuid":"187499284","full_name":"Cysharp/UniTask","owner":"Cysharp","description":"Provides an efficient allocation free async/await integration for Unity.","archived":false,"fork":false,"pushed_at":"2025-03-19T06:44:21.000Z","size":5946,"stargazers_count":9139,"open_issues_count":19,"forks_count":898,"subscribers_count":118,"default_branch":"master","last_synced_at":"2025-04-22T01:55:25.402Z","etag":null,"topics":["coroutine","csharp","task","thread","unity"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Cysharp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["neuecc"]}},"created_at":"2019-05-19T16:09:55.000Z","updated_at":"2025-04-22T01:31:16.000Z","dependencies_parsed_at":"2023-02-09T03:15:28.977Z","dependency_job_id":"692e94ef-de83-4a42-97e3-13ca0c4f8b12","html_url":"https://github.com/Cysharp/UniTask","commit_stats":{"total_commits":677,"total_committers":58,"mean_commits":"11.672413793103448","dds":"0.37813884785819796","last_synced_commit":"2e0917428bc49a88f8bb90f3cbdeabd4d978ae30"},"previous_names":[],"tags_count":71,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cysharp%2FUniTask","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cysharp%2FUniTask/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cysharp%2FUniTask/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cysharp%2FUniTask/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Cysharp","download_url":"https://codeload.github.com/Cysharp/UniTask/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250825196,"owners_count":21493407,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coroutine","csharp","task","thread","unity"],"created_at":"2024-08-02T05:02:25.728Z","updated_at":"2025-04-25T13:33:02.325Z","avatar_url":"https://github.com/Cysharp.png","language":"C#","readme":"UniTask\n===\n[![GitHub Actions](https://github.com/Cysharp/UniTask/workflows/Build-Debug/badge.svg)](https://github.com/Cysharp/UniTask/actions) [![Releases](https://img.shields.io/github/release/Cysharp/UniTask.svg)](https://github.com/Cysharp/UniTask/releases) [![Readme_CN](https://img.shields.io/badge/UniTask-%E4%B8%AD%E6%96%87%E6%96%87%E6%A1%A3-red)](https://github.com/Cysharp/UniTask/blob/master/README_CN.md)\n\nProvides an efficient allocation free async/await integration for Unity.\n\n* Struct based `UniTask\u003cT\u003e` and custom AsyncMethodBuilder to achieve zero allocation\n* Makes all Unity AsyncOperations and Coroutines awaitable\n* PlayerLoop based task(`UniTask.Yield`, `UniTask.Delay`, `UniTask.DelayFrame`, etc..) that enable replacing all coroutine operations\n* MonoBehaviour Message Events and uGUI Events as awaitable/async-enumerable\n* Runs completely on Unity's PlayerLoop so doesn't use threads and runs on WebGL, wasm, etc.\n* Asynchronous LINQ, with Channel and AsyncReactiveProperty\n* TaskTracker window to prevent memory leaks\n* Highly compatible behaviour with Task/ValueTask/IValueTaskSource\n\nFor technical details, see blog post: [UniTask v2 — Zero Allocation async/await for Unity, with Asynchronous LINQ\n](https://medium.com/@neuecc/unitask-v2-zero-allocation-async-await-for-unity-with-asynchronous-linq-1aa9c96aa7dd)  \nFor advanced tips, see blog post: [Extends UnityWebRequest via async decorator pattern — Advanced Techniques of UniTask](https://medium.com/@neuecc/extends-unitywebrequest-via-async-decorator-pattern-advanced-techniques-of-unitask-ceff9c5ee846)\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n## Table of Contents\n\n- [Getting started](#getting-started)\n- [Basics of UniTask and AsyncOperation](#basics-of-unitask-and-asyncoperation)\n- [Cancellation and Exception handling](#cancellation-and-exception-handling)\n- [Timeout handling](#timeout-handling)\n- [Progress](#progress)\n- [PlayerLoop](#playerloop)\n- [async void vs async UniTaskVoid](#async-void-vs-async-unitaskvoid)\n- [UniTaskTracker](#unitasktracker)\n- [External Assets](#external-assets)\n- [AsyncEnumerable and Async LINQ](#asyncenumerable-and-async-linq)\n- [Awaitable Events](#awaitable-events)\n- [Channel](#channel)\n- [vs Awaitable](#vs-awaitable)\n- [For Unit Testing](#for-unit-testing)\n- [ThreadPool limitation](#threadpool-limitation)\n- [IEnumerator.ToUniTask limitation](#ienumeratortounitask-limitation)\n- [For UnityEditor](#for-unityeditor)\n- [Compare with Standard Task API](#compare-with-standard-task-api)\n- [Pooling Configuration](#pooling-configuration)\n- [Allocation on Profiler](#allocation-on-profiler)\n- [UniTaskSynchronizationContext](#unitasksynchronizationcontext)\n- [API References](#api-references)\n- [UPM Package](#upm-package)\n  - [Install via git URL](#install-via-git-url)\n- [.NET Core](#net-core)\n- [License](#license)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\nGetting started\n---\nInstall via [UPM package](#upm-package) with git reference or asset package(`UniTask.*.*.*.unitypackage`) available in [UniTask/releases](https://github.com/Cysharp/UniTask/releases).\n\n```csharp\n// extension awaiter/methods can be used by this namespace\nusing Cysharp.Threading.Tasks;\n\n// You can return type as struct UniTask\u003cT\u003e(or UniTask), it is unity specialized lightweight alternative of Task\u003cT\u003e\n// zero allocation and fast excution for zero overhead async/await integrate with Unity\nasync UniTask\u003cstring\u003e DemoAsync()\n{\n    // You can await Unity's AsyncObject\n    var asset = await Resources.LoadAsync\u003cTextAsset\u003e(\"foo\");\n    var txt = (await UnityWebRequest.Get(\"https://...\").SendWebRequest()).downloadHandler.text;\n    await SceneManager.LoadSceneAsync(\"scene2\");\n\n    // .WithCancellation enables Cancel, GetCancellationTokenOnDestroy synchornizes with lifetime of GameObject\n    // after Unity 2022.2, you can use `destroyCancellationToken` in MonoBehaviour\n    var asset2 = await Resources.LoadAsync\u003cTextAsset\u003e(\"bar\").WithCancellation(this.GetCancellationTokenOnDestroy());\n\n    // .ToUniTask accepts progress callback(and all options), Progress.Create is a lightweight alternative of IProgress\u003cT\u003e\n    var asset3 = await Resources.LoadAsync\u003cTextAsset\u003e(\"baz\").ToUniTask(Progress.Create\u003cfloat\u003e(x =\u003e Debug.Log(x)));\n\n    // await frame-based operation like a coroutine\n    await UniTask.DelayFrame(100); \n\n    // replacement of yield return new WaitForSeconds/WaitForSecondsRealtime\n    await UniTask.Delay(TimeSpan.FromSeconds(10), ignoreTimeScale: false);\n    \n    // yield any playerloop timing(PreUpdate, Update, LateUpdate, etc...)\n    await UniTask.Yield(PlayerLoopTiming.PreLateUpdate);\n\n    // replacement of yield return null\n    await UniTask.Yield();\n    await UniTask.NextFrame();\n\n    // replacement of WaitForEndOfFrame\n#if UNITY_2023_1_OR_NEWER\n    await UniTask.WaitForEndOfFrame();\n#else\n    // requires MonoBehaviour(CoroutineRunner))\n    await UniTask.WaitForEndOfFrame(this); // this is MonoBehaviour\n#endif\n\n    // replacement of yield return new WaitForFixedUpdate(same as UniTask.Yield(PlayerLoopTiming.FixedUpdate))\n    await UniTask.WaitForFixedUpdate();\n    \n    // replacement of yield return WaitUntil\n    await UniTask.WaitUntil(() =\u003e isActive == false);\n\n    // special helper of WaitUntil\n    await UniTask.WaitUntilValueChanged(this, x =\u003e x.isActive);\n\n    // You can await IEnumerator coroutines\n    await FooCoroutineEnumerator();\n\n    // You can await a standard task\n    await Task.Run(() =\u003e 100);\n\n    // Multithreading, run on ThreadPool under this code\n    await UniTask.SwitchToThreadPool();\n\n    /* work on ThreadPool */\n\n    // return to MainThread(same as `ObserveOnMainThread` in UniRx)\n    await UniTask.SwitchToMainThread();\n\n    // get async webrequest\n    async UniTask\u003cstring\u003e GetTextAsync(UnityWebRequest req)\n    {\n        var op = await req.SendWebRequest();\n        return op.downloadHandler.text;\n    }\n\n    var task1 = GetTextAsync(UnityWebRequest.Get(\"http://google.com\"));\n    var task2 = GetTextAsync(UnityWebRequest.Get(\"http://bing.com\"));\n    var task3 = GetTextAsync(UnityWebRequest.Get(\"http://yahoo.com\"));\n\n    // concurrent async-wait and get results easily by tuple syntax\n    var (google, bing, yahoo) = await UniTask.WhenAll(task1, task2, task3);\n\n    // shorthand of WhenAll, tuple can await directly\n    var (google2, bing2, yahoo2) = await (task1, task2, task3);\n\n    // return async-value.(or you can use `UniTask`(no result), `UniTaskVoid`(fire and forget)).\n    return (asset as TextAsset)?.text ?? throw new InvalidOperationException(\"Asset not found\");\n}\n```\n\nBasics of UniTask and AsyncOperation\n---\nUniTask features rely on C# 7.0([task-like custom async method builder feature](https://github.com/dotnet/roslyn/blob/master/docs/features/task-types.md)) so the required Unity version is after `Unity 2018.3`, the official lowest version supported is `Unity 2018.4.13f1`.\n\nWhy is UniTask(custom task-like object) required? Because Task is too heavy and not matched to Unity threading (single-thread). UniTask does not use threads and SynchronizationContext/ExecutionContext because Unity's asynchronous object is automaticaly dispatched by Unity's engine layer. It achieves faster and lower allocation, and is completely integrated with Unity.\n\nYou can await `AsyncOperation`, `ResourceRequest`, `AssetBundleRequest`, `AssetBundleCreateRequest`, `UnityWebRequestAsyncOperation`, `AsyncGPUReadbackRequest`, `IEnumerator` and others when `using Cysharp.Threading.Tasks;`.\n\nUniTask provides three pattern of extension methods.\n\n```csharp\n* await asyncOperation;\n* .WithCancellation(CancellationToken);\n* .ToUniTask(IProgress, PlayerLoopTiming, CancellationToken);\n```\n\n`WithCancellation` is a simple version of `ToUniTask`, both return `UniTask`. For details of cancellation, see: [Cancellation and Exception handling](#cancellation-and-exception-handling) section.\n\n\u003e Note: await directly is returned from native timing of PlayerLoop but WithCancellation and ToUniTask are returned from specified PlayerLoopTiming. For details of timing, see: [PlayerLoop](#playerloop) section.\n\n\u003e Note: AssetBundleRequest has `asset` and `allAssets`, default await returns `asset`. If you want to get `allAssets`, you can use `AwaitForAllAssets()` method.\n\nThe type of `UniTask` can use utilities like `UniTask.WhenAll`, `UniTask.WhenAny`, `UniTask.WhenEach`. They are like `Task.WhenAll`/`Task.WhenAny` but the return type is more useful. They return value tuples so you can deconstruct each result and pass multiple types.\n\n```csharp\npublic async UniTaskVoid LoadManyAsync()\n{\n    // parallel load.\n    var (a, b, c) = await UniTask.WhenAll(\n        LoadAsSprite(\"foo\"),\n        LoadAsSprite(\"bar\"),\n        LoadAsSprite(\"baz\"));\n}\n\nasync UniTask\u003cSprite\u003e LoadAsSprite(string path)\n{\n    var resource = await Resources.LoadAsync\u003cSprite\u003e(path);\n    return (resource as Sprite);\n}\n```\n\nIf you want to convert a callback to UniTask, you can use `UniTaskCompletionSource\u003cT\u003e` which is a lightweight edition of `TaskCompletionSource\u003cT\u003e`. \n\n```csharp\npublic UniTask\u003cint\u003e WrapByUniTaskCompletionSource()\n{\n    var utcs = new UniTaskCompletionSource\u003cint\u003e();\n\n    // when complete, call utcs.TrySetResult();\n    // when failed, call utcs.TrySetException();\n    // when cancel, call utcs.TrySetCanceled();\n\n    return utcs.Task; //return UniTask\u003cint\u003e\n}\n```\n\nYou can convert Task -\u003e UniTask: `AsUniTask`, `UniTask` -\u003e `UniTask\u003cAsyncUnit\u003e`: `AsAsyncUnitUniTask`, `UniTask\u003cT\u003e` -\u003e `UniTask`: `AsUniTask`. `UniTask\u003cT\u003e` -\u003e `UniTask`'s conversion cost is free.\n\nIf you want to convert async to coroutine, you can use `.ToCoroutine()`, this is useful if you want to only allow using the coroutine system.\n\nUniTask can not await twice. This is a similar constraint to the [ValueTask/IValueTaskSource](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1?view=netcore-3.1) introduced in .NET Standard 2.1.\n\n\u003e The following operations should never be performed on a ValueTask\u003cTResult\u003e instance:\n\u003e\n\u003e * Awaiting the instance multiple times.\n\u003e * Calling AsTask multiple times.\n\u003e * Using .Result or .GetAwaiter().GetResult() when the operation hasn't yet completed, or using them multiple times.\n\u003e * Using more than one of these techniques to consume the instance.\n\u003e\n\u003e If you do any of the above, the results are undefined.\n\n```csharp\nvar task = UniTask.DelayFrame(10);\nawait task;\nawait task; // NG, throws Exception\n```\n\nStore to the class field, you can use `UniTask.Lazy` that supports calling multiple times. `.Preserve()` allows for multiple calls (internally cached results). This is useful when there are multiple calls in a function scope.\n\nAlso `UniTaskCompletionSource` can await multiple times and await from many callers.\n\nCancellation and Exception handling\n---\nSome UniTask factory methods have a `CancellationToken cancellationToken = default` parameter. Also some async operations for Unity have `WithCancellation(CancellationToken)` and `ToUniTask(..., CancellationToken cancellation = default)` extension methods. \n\nYou can pass `CancellationToken` to parameter by standard [`CancellationTokenSource`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource).\n\n```csharp\nvar cts = new CancellationTokenSource();\n\ncancelButton.onClick.AddListener(() =\u003e\n{\n    cts.Cancel();\n});\n\nawait UnityWebRequest.Get(\"http://google.co.jp\").SendWebRequest().WithCancellation(cts.Token);\n\nawait UniTask.DelayFrame(1000, cancellationToken: cts.Token);\n```\n\nCancellationToken can be created by `CancellationTokenSource` or MonoBehaviour's extension method `GetCancellationTokenOnDestroy`.\n\n```csharp\n// this CancellationToken lifecycle is same as GameObject.\nawait UniTask.DelayFrame(1000, cancellationToken: this.GetCancellationTokenOnDestroy());\n```\n\nFor propagate Cancellation, all async method recommend to accept `CancellationToken cancellationToken` at last argument, and pass `CancellationToken` from root to end.\n\n```csharp\nawait FooAsync(this.GetCancellationTokenOnDestroy());\n\n// ---\n\nasync UniTask FooAsync(CancellationToken cancellationToken)\n{\n    await BarAsync(cancellationToken);\n}\n\nasync UniTask BarAsync(CancellationToken cancellationToken)\n{\n    await UniTask.Delay(TimeSpan.FromSeconds(3), cancellationToken);\n}\n```\n\n`CancellationToken` means lifecycle of async. You can hold your own lifecycle insteadof default CancellationTokenOnDestroy.\n\n```csharp\npublic class MyBehaviour : MonoBehaviour\n{\n    CancellationTokenSource disableCancellation = new CancellationTokenSource();\n    CancellationTokenSource destroyCancellation = new CancellationTokenSource();\n\n    private void OnEnable()\n    {\n        if (disableCancellation != null)\n        {\n            disableCancellation.Dispose();\n        }\n        disableCancellation = new CancellationTokenSource();\n    }\n\n    private void OnDisable()\n    {\n        disableCancellation.Cancel();\n    }\n\n    private void OnDestroy()\n    {\n        destroyCancellation.Cancel();\n        destroyCancellation.Dispose();\n    }\n}\n```\n\nAfter Unity 2022.2, Unity adds CancellationToken in [MonoBehaviour.destroyCancellationToken](https://docs.unity3d.com/ScriptReference/MonoBehaviour-destroyCancellationToken.html) and [Application.exitCancellationToken](https://docs.unity3d.com/ScriptReference/Application-exitCancellationToken.html).\n\nWhen cancellation is detected, all methods throw `OperationCanceledException` and propagate upstream. When exception(not limited to `OperationCanceledException`) is not handled in async method, it is propagated finally to `UniTaskScheduler.UnobservedTaskException`. The default behaviour of received unhandled exception is to write log as exception. Log level can be changed using `UniTaskScheduler.UnobservedExceptionWriteLogType`. If you want to use custom behaviour, set an action to `UniTaskScheduler.UnobservedTaskException.`\n\nAnd also `OperationCanceledException` is a special exception, this is silently ignored at `UnobservedTaskException`.\n\nIf you want to cancel behaviour in an async UniTask method, throw `OperationCanceledException` manually.\n\n```csharp\npublic async UniTask\u003cint\u003e FooAsync()\n{\n    await UniTask.Yield();\n    throw new OperationCanceledException();\n}\n```\n\nIf you handle an exception but want to ignore(propagate to global cancellation handling), use an exception filter.\n\n```csharp\npublic async UniTask\u003cint\u003e BarAsync()\n{\n    try\n    {\n        var x = await FooAsync();\n        return x * 2;\n    }\n    catch (Exception ex) when (!(ex is OperationCanceledException)) // when (ex is not OperationCanceledException) at C# 9.0\n    {\n        return -1;\n    }\n}\n```\n\nthrows/catch `OperationCanceledException` is slightly heavy, so if performance is a concern, use `UniTask.SuppressCancellationThrow` to avoid OperationCanceledException throw. It returns `(bool IsCanceled, T Result)` instead of throwing.\n\n```csharp\nvar (isCanceled, _) = await UniTask.DelayFrame(10, cancellationToken: cts.Token).SuppressCancellationThrow();\nif (isCanceled)\n{\n    // ...\n}\n```\n\nNote: Only suppress throws if you call directly into the most source method. Otherwise, the return value will be converted, but the entire pipeline will not suppress throws.\n\nSome features that use Unity's player loop, such as `UniTask.Yield` and `UniTask.Delay` etc, determines CancellationToken state on the player loop. \nThis means it does not cancel immediately upon `CancellationToken` fired. \n\nIf you want to change this behaviour, the cancellation to be immediate, set the `cancelImmediately` flag as an argument.\n\n```csharp\nawait UniTask.Yield(cancellationToken, cancelImmediately: true);\n```\n\nNote: Setting `cancelImmediately` to true and detecting an immediate cancellation is more costly than the default behavior.\nThis is because it uses `CancellationToken.Register`; it is heavier than checking CancellationToken on the player loop.\n\nTimeout handling\n---\nTimeout is a variation of cancellation. You can set timeout by `CancellationTokenSouce.CancelAfterSlim(TimeSpan)` and pass CancellationToken to async methods.\n\n```csharp\nvar cts = new CancellationTokenSource();\ncts.CancelAfterSlim(TimeSpan.FromSeconds(5)); // 5sec timeout.\n\ntry\n{\n    await UnityWebRequest.Get(\"http://foo\").SendWebRequest().WithCancellation(cts.Token);\n}\ncatch (OperationCanceledException ex)\n{\n    if (ex.CancellationToken == cts.Token)\n    {\n        UnityEngine.Debug.Log(\"Timeout\");\n    }\n}\n```\n\n\u003e `CancellationTokenSouce.CancelAfter` is a standard api. However in Unity you should not use it because it depends threading timer. `CancelAfterSlim` is UniTask's extension methods, it uses PlayerLoop instead.\n\nIf you want to use timeout with other source of cancellation, use `CancellationTokenSource.CreateLinkedTokenSource`.\n\n```csharp\nvar cancelToken = new CancellationTokenSource();\ncancelButton.onClick.AddListener(() =\u003e\n{\n    cancelToken.Cancel(); // cancel from button click.\n});\n\nvar timeoutToken = new CancellationTokenSource();\ntimeoutToken.CancelAfterSlim(TimeSpan.FromSeconds(5)); // 5sec timeout.\n\ntry\n{\n    // combine token\n    var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancelToken.Token, timeoutToken.Token);\n\n    await UnityWebRequest.Get(\"http://foo\").SendWebRequest().WithCancellation(linkedTokenSource.Token);\n}\ncatch (OperationCanceledException ex)\n{\n    if (timeoutToken.IsCancellationRequested)\n    {\n        UnityEngine.Debug.Log(\"Timeout.\");\n    }\n    else if (cancelToken.IsCancellationRequested)\n    {\n        UnityEngine.Debug.Log(\"Cancel clicked.\");\n    }\n}\n```\n\nOptimize for reduce allocation of CancellationTokenSource for timeout per call async method, you can use UniTask's `TimeoutController`.\n\n```csharp\nTimeoutController timeoutController = new TimeoutController(); // setup to field for reuse.\n\nasync UniTask FooAsync()\n{\n    try\n    {\n        // you can pass timeoutController.Timeout(TimeSpan) to cancellationToken.\n        await UnityWebRequest.Get(\"http://foo\").SendWebRequest()\n            .WithCancellation(timeoutController.Timeout(TimeSpan.FromSeconds(5)));\n        timeoutController.Reset(); // call Reset(Stop timeout timer and ready for reuse) when succeed.\n    }\n    catch (OperationCanceledException ex)\n    {\n        if (timeoutController.IsTimeout())\n        {\n            UnityEngine.Debug.Log(\"timeout\");\n        }\n    }\n}\n```\n\nIf you want to use timeout with other source of cancellation, use `new TimeoutController(CancellationToken)`.\n\n```csharp\nTimeoutController timeoutController;\nCancellationTokenSource clickCancelSource;\n\nvoid Start()\n{\n    this.clickCancelSource = new CancellationTokenSource();\n    this.timeoutController = new TimeoutController(clickCancelSource);\n}\n```\n\nNote: UniTask has `.Timeout`, `.TimeoutWithoutException` methods however, if possible, do not use these, please pass `CancellationToken`. Because `.Timeout` work from external of task, can not stop timeoutted task. `.Timeout` means ignore result when timeout. If you pass a `CancellationToken` to the method, it will act from inside of the task, so it is possible to stop a running task.\n\nProgress\n---\nSome async operations for unity have `ToUniTask(IProgress\u003cfloat\u003e progress = null, ...)` extension methods. \n\n```csharp\nvar progress = Progress.Create\u003cfloat\u003e(x =\u003e Debug.Log(x));\n\nvar request = await UnityWebRequest.Get(\"http://google.co.jp\")\n    .SendWebRequest()\n    .ToUniTask(progress: progress);\n```\n\nYou should not use standard `new System.Progress\u003cT\u003e`, because it causes allocation every time. Use `Cysharp.Threading.Tasks.Progress` instead. This progress factory has two methods, `Create` and `CreateOnlyValueChanged`. `CreateOnlyValueChanged` calls only when the progress value has changed.\n\nImplementing IProgress interface to caller is better as there is no lambda allocation.\n\n```csharp\npublic class Foo : MonoBehaviour, IProgress\u003cfloat\u003e\n{\n    public void Report(float value)\n    {\n        UnityEngine.Debug.Log(value);\n    }\n\n    public async UniTaskVoid WebRequest()\n    {\n        var request = await UnityWebRequest.Get(\"http://google.co.jp\")\n            .SendWebRequest()\n            .ToUniTask(progress: this); // pass this\n    }\n}\n```\n\nPlayerLoop\n---\nUniTask is run on a custom [PlayerLoop](https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html). UniTask's playerloop based methods (such as `Delay`, `DelayFrame`, `asyncOperation.ToUniTask`, etc...) accept this `PlayerLoopTiming`.\n\n```csharp\npublic enum PlayerLoopTiming\n{\n    Initialization = 0,\n    LastInitialization = 1,\n\n    EarlyUpdate = 2,\n    LastEarlyUpdate = 3,\n\n    FixedUpdate = 4,\n    LastFixedUpdate = 5,\n\n    PreUpdate = 6,\n    LastPreUpdate = 7,\n\n    Update = 8,\n    LastUpdate = 9,\n\n    PreLateUpdate = 10,\n    LastPreLateUpdate = 11,\n\n    PostLateUpdate = 12,\n    LastPostLateUpdate = 13\n    \n#if UNITY_2020_2_OR_NEWER\n    TimeUpdate = 14,\n    LastTimeUpdate = 15,\n#endif\n}\n```\n\nIt indicates when to run, you can check [PlayerLoopList.md](https://gist.github.com/neuecc/bc3a1cfd4d74501ad057e49efcd7bdae) to Unity's default playerloop and injected UniTask's custom loop.\n\n`PlayerLoopTiming.Update` is similar to `yield return null` in a coroutine, but it is called before Update(Update and uGUI events(button.onClick, etc...) are called on `ScriptRunBehaviourUpdate`, yield return null is called on `ScriptRunDelayedDynamicFrameRate`). `PlayerLoopTiming.FixedUpdate` is similar to `WaitForFixedUpdate`.\n\n\u003e `PlayerLoopTiming.LastPostLateUpdate` is not equivalent to coroutine's `yield return new WaitForEndOfFrame()`. Coroutine's WaitForEndOfFrame seems to run after the PlayerLoop is done. Some methods that require coroutine's end of frame(`Texture2D.ReadPixels`, `ScreenCapture.CaptureScreenshotAsTexture`, `CommandBuffer`, etc) do not work correctly when replaced with async/await. In these cases, pass MonoBehaviour(coroutine runnner) to `UniTask.WaitForEndOfFrame`. For example, `await UniTask.WaitForEndOfFrame(this);` is lightweight allocation free alternative of `yield return new WaitForEndOfFrame()`.\n\u003e \n\u003e Note: In Unity 2023.1 or newer, `await UniTask.WaitForEndOfFrame();` no longer requires MonoBehaviour. It uses `UnityEngine.Awaitable.EndOfFrameAsync`.\n\n`yield return null` and `UniTask.Yield` are similar but different. `yield return null` always returns next frame but `UniTask.Yield` returns next called. That is, call `UniTask.Yield(PlayerLoopTiming.Update)` on `PreUpdate`, it returns same frame. `UniTask.NextFrame()` guarantees return next frame, you can expect this to behave exactly the same as `yield return null`.\n\n\u003e UniTask.Yield(without CancellationToken) is a special type, returns `YieldAwaitable` and runs on YieldRunner. It is the most lightweight and fastest.\n\n`AsyncOperation` is returned from native timing. For example, await `SceneManager.LoadSceneAsync` is returned from `EarlyUpdate.UpdatePreloading` and after being called, the loaded scene's `Start` is called from `EarlyUpdate.ScriptRunDelayedStartupFrame`. Also `await UnityWebRequest` is returned from `EarlyUpdate.ExecuteMainThreadJobs`.\n\nIn UniTask, await directly uses native timing, while `WithCancellation` and `ToUniTask` use specified timing. This is usually not a particular problem, but with `LoadSceneAsync`, it causes a different order of Start and continuation after await. So it is recommended not to use `LoadSceneAsync.ToUniTask`.\n\n\u003e Note: When using Unity 2023.1 or newer, ensure you have `using UnityEngine;` in the using statements of your file when working with new `UnityEngine.Awaitable` methods like `SceneManager.LoadSceneAsync`. \n\u003e This prevents compilation errors by avoiding the use of the `UnityEngine.AsyncOperation` version.\n\nIn the stacktrace, you can check where it is running in playerloop.\n\n![image](https://user-images.githubusercontent.com/46207/83735571-83caea80-a68b-11ea-8d22-5e22864f0d24.png)\n\nBy default, UniTask's PlayerLoop is initialized at `[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]`.\n\nThe order in which methods are called in BeforeSceneLoad is nondeterministic, so if you want to use UniTask in other BeforeSceneLoad methods, you should try to initialize it before this.\n\n```csharp\n// AfterAssembliesLoaded is called before BeforeSceneLoad\n[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]\npublic static void InitUniTaskLoop()\n{\n    var loop = PlayerLoop.GetCurrentPlayerLoop();\n    Cysharp.Threading.Tasks.PlayerLoopHelper.Initialize(ref loop);\n}\n```\n\nIf you import Unity's `Entities` package, that resets the custom player loop to default at `BeforeSceneLoad` and injects ECS's loop. When Unity calls ECS's inject method after UniTask's initialize method, UniTask will no longer work.\n\nTo solve this issue, you can re-initialize the UniTask PlayerLoop after ECS is initialized.\n\n```csharp\n// Get ECS Loop.\nvar playerLoop = ScriptBehaviourUpdateOrder.CurrentPlayerLoop;\n\n// Setup UniTask's PlayerLoop.\nPlayerLoopHelper.Initialize(ref playerLoop);\n```\n\nYou can diagnose whether UniTask's player loop is ready by calling `PlayerLoopHelper.IsInjectedUniTaskPlayerLoop()`. And also `PlayerLoopHelper.DumpCurrentPlayerLoop` logs all current playerloops to console.\n\n```csharp\nvoid Start()\n{\n    UnityEngine.Debug.Log(\"UniTaskPlayerLoop ready? \" + PlayerLoopHelper.IsInjectedUniTaskPlayerLoop());\n    PlayerLoopHelper.DumpCurrentPlayerLoop();\n}\n```\n\nYou can optimize loop cost slightly by remove unuse PlayerLoopTiming injection. You can call `PlayerLoopHelper.Initialize(InjectPlayerLoopTimings)` on initialize.\n\n```csharp\nvar loop = PlayerLoop.GetCurrentPlayerLoop();\nPlayerLoopHelper.Initialize(ref loop, InjectPlayerLoopTimings.Minimum); // minimum is Update | FixedUpdate | LastPostLateUpdate\n```\n\n`InjectPlayerLoopTimings` has three preset, `All` and `Standard`(All without last except LastPostLateUpdate), `Minimum`(`Update | FixedUpdate | LastPostLateUpdate`). Default is All and you can combine custom inject timings like `InjectPlayerLoopTimings.Update | InjectPlayerLoopTimings.FixedUpdate | InjectPlayerLoopTimings.PreLateUpdate`.\n\nYou can make error to use uninjected `PlayerLoopTiming` by [Microsoft.CodeAnalysis.BannedApiAnalyzers](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md). For example, you can setup `BannedSymbols.txt` like this for `InjectPlayerLoopTimings.Minimum`.\n\n```txt\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.Initialization; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastInitialization; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.EarlyUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastEarlyUpdate; Isn't injected this PlayerLoop in this project.d\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastFixedUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.PreUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastPreUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.PreLateUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastPreLateUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.PostLateUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.TimeUpdate; Isn't injected this PlayerLoop in this project.\nF:Cysharp.Threading.Tasks.PlayerLoopTiming.LastTimeUpdate; Isn't injected this PlayerLoop in this project.\n```\n\nYou can configure `RS0030` severity to error.\n\n![image](https://user-images.githubusercontent.com/46207/109150837-bb933880-77ac-11eb-85ba-4fd15819dbd0.png)\n\nasync void vs async UniTaskVoid\n---\n`async void` is a standard C# task system so it does not run on UniTask systems. It is better not to use it. `async UniTaskVoid` is a lightweight version of `async UniTask` because it does not have awaitable completion and reports errors immediately to `UniTaskScheduler.UnobservedTaskException`. If you don't require awaiting (fire and forget), using `UniTaskVoid` is better. Unfortunately to dismiss warning, you're required to call `Forget()`.\n\n```csharp\npublic async UniTaskVoid FireAndForgetMethod()\n{\n    // do anything...\n    await UniTask.Yield();\n}\n\npublic void Caller()\n{\n    FireAndForgetMethod().Forget();\n}\n```\n\nAlso UniTask has the `Forget` method, it is similar to `UniTaskVoid` and has the same effects. However `UniTaskVoid` is more efficient if you completely don't use `await`。\n\n```csharp\npublic async UniTask DoAsync()\n{\n    // do anything...\n    await UniTask.Yield();\n}\n\npublic void Caller()\n{\n    DoAsync().Forget();\n}\n```\n\nTo use an async lambda registered to an event, don't use `async void`. Instead you can use `UniTask.Action` or `UniTask.UnityAction`, both of which create a delegate via `async UniTaskVoid` lambda.\n\n```csharp\nAction actEvent;\nUnityAction unityEvent; // especially used in uGUI\n\n// Bad: async void\nactEvent += async () =\u003e { };\nunityEvent += async () =\u003e { };\n\n// Ok: create Action delegate by lambda\nactEvent += UniTask.Action(async () =\u003e { await UniTask.Yield(); });\nunityEvent += UniTask.UnityAction(async () =\u003e { await UniTask.Yield(); });\n```\n\n`UniTaskVoid` can also be used in MonoBehaviour's `Start` method.\n\n```csharp\nclass Sample : MonoBehaviour\n{\n    async UniTaskVoid Start()\n    {\n        // async init code.\n    }\n}\n```\n\nUniTaskTracker\n---\nuseful for checking (leaked) UniTasks. You can open tracker window in `Window -\u003e UniTask Tracker`.\n\n![image](https://user-images.githubusercontent.com/46207/83527073-4434bf00-a522-11ea-86e9-3b3975b26266.png)\n\n* Enable AutoReload(Toggle) - Reload automatically.\n* Reload - Reload view.\n* GC.Collect - Invoke GC.Collect.\n* Enable Tracking(Toggle) - Start to track async/await UniTask. Performance impact: low.\n* Enable StackTrace(Toggle) - Capture StackTrace when task is started. Performance impact: high.\n\nUniTaskTracker is intended for debugging use only as enabling tracking and capturing stacktraces is useful but has a heavy performance impact. Recommended usage is to enable both tracking and stacktraces to find task leaks and to disable them both when done.\n\nExternal Assets\n---\nBy default, UniTask supports TextMeshPro(`BindTo(TMP_Text)` and `TMP_InputField` event extensions like standard uGUI `InputField`), DOTween(`Tween` as awaitable) and Addressables(`AsyncOperationHandle` and `AsyncOperationHandle\u003cT\u003e` as awaitable).\n\nThere are defined in separated asmdefs like `UniTask.TextMeshPro`, `UniTask.DOTween`, `UniTask.Addressables`.\n\nTextMeshPro and Addressables support are automatically enabled when importing their packages from package manager. \nHowever for DOTween support, after importing from the [DOTWeen assets](https://assetstore.unity.com/packages/tools/animation/dotween-hotween-v2-27676r) and define the scripting define symbol `UNITASK_DOTWEEN_SUPPORT` to enable it.\n\n```csharp\n// sequential\nawait transform.DOMoveX(2, 10);\nawait transform.DOMoveZ(5, 20);\n\n// parallel with cancellation\nvar ct = this.GetCancellationTokenOnDestroy();\n\nawait UniTask.WhenAll(\n    transform.DOMoveX(10, 3).WithCancellation(ct),\n    transform.DOScale(10, 3).WithCancellation(ct));\n```\n\nDOTween support's default behaviour(`await`, `WithCancellation`, `ToUniTask`) awaits tween is killed. It works on both Complete(true/false) and Kill(true/false). But if you want to reuse tweens (`SetAutoKill(false)`), it does not work as expected. If you want to await for another timing, the following extension methods exist in Tween, `AwaitForComplete`, `AwaitForPause`, `AwaitForPlay`, `AwaitForRewind`, `AwaitForStepComplete`.\n\nAsyncEnumerable and Async LINQ\n---\nUnity 2020.2 supports C# 8.0 so you can use `await foreach`. This is the new Update notation in the async era.\n\n```csharp\n// Unity 2020.2, C# 8.0\nawait foreach (var _ in UniTaskAsyncEnumerable.EveryUpdate().WithCancellation(token))\n{\n    Debug.Log(\"Update() \" + Time.frameCount);\n}\n```\n\nIn a C# 7.3 environment, you can use the `ForEachAsync` method to work in almost the same way.\n\n```csharp\n// C# 7.3(Unity 2018.3~)\nawait UniTaskAsyncEnumerable.EveryUpdate().ForEachAsync(_ =\u003e\n{\n    Debug.Log(\"Update() \" + Time.frameCount);\n}, token);\n```\n\n`UniTask.WhenEach` that is similar to .NET 9's `Task.WhenEach` can consume new way for await multiple tasks.\n\n```csharp\nawait foreach (var result in UniTask.WhenEach(task1, task2, task3))\n{\n    // The result is of type WhenEachResult\u003cT\u003e.\n    // It contains either `T Result` or `Exception Exception`.\n    // You can check `IsCompletedSuccessfully` or `IsFaulted` to determine whether to access `.Result` or `.Exception`.\n    // If you want to throw an exception when `IsFaulted` and retrieve the result when successful, use `GetResult()`.\n    Debug.Log(result.GetResult());\n}\n```\n\nUniTaskAsyncEnumerable implements asynchronous LINQ, similar to LINQ in `IEnumerable\u003cT\u003e` or Rx in `IObservable\u003cT\u003e`. All standard LINQ query operators can be applied to asynchronous streams. For example, the following code shows how to apply a Where filter to a button-click asynchronous stream that runs once every two clicks.\n\n```csharp\nawait okButton.OnClickAsAsyncEnumerable().Where((x, i) =\u003e i % 2 == 0).ForEachAsync(_ =\u003e\n{\n});\n```\n\nFire and Forget style(for example, event handling), you can also use `Subscribe`.\n\n```csharp\nokButton.OnClickAsAsyncEnumerable().Where((x, i) =\u003e i % 2 == 0).Subscribe(_ =\u003e\n{\n});\n```\n\nAsync LINQ is enabled when `using Cysharp.Threading.Tasks.Linq;`, and `UniTaskAsyncEnumerable` is defined in `UniTask.Linq` asmdef.\n\nIt's closer to UniRx (Reactive Extensions), but UniTaskAsyncEnumerable is a pull-based asynchronous stream, whereas Rx was a push-based asynchronous stream. Note that although similar, the characteristics are different and the details behave differently along with them.\n\n`UniTaskAsyncEnumerable` is the entry point like `Enumerable`. In addition to the standard query operators, there are other generators for Unity such as `EveryUpdate`, `Timer`, `TimerFrame`, `Interval`, `IntervalFrame`, and `EveryValueChanged`. And also added additional UniTask original query operators like `Append`, `Prepend`, `DistinctUntilChanged`, `ToHashSet`, `Buffer`, `CombineLatest`,`Merge` `Do`, `Never`, `ForEachAsync`, `Pairwise`, `Publish`, `Queue`, `Return`, `SkipUntil`, `TakeUntil`, `SkipUntilCanceled`, `TakeUntilCanceled`, `TakeLast`, `Subscribe`.\n\nThe method with Func as an argument has three additional overloads, `***Await`, `***AwaitWithCancellation`.\n\n```csharp\nSelect(Func\u003cT, TR\u003e selector)\nSelectAwait(Func\u003cT, UniTask\u003cTR\u003e\u003e selector)\nSelectAwaitWithCancellation(Func\u003cT, CancellationToken, UniTask\u003cTR\u003e\u003e selector)\n```\n\nIf you want to use the `async` method inside the func, use the `***Await` or `***AwaitWithCancellation`.\n\nHow to create an async iterator: C# 8.0 supports async iterator(`async yield return`) but it only allows `IAsyncEnumerable\u003cT\u003e` and of course requires C# 8.0. UniTask supports `UniTaskAsyncEnumerable.Create` method to create custom async iterator.\n\n```csharp\n// IAsyncEnumerable, C# 8.0 version of async iterator. ( do not use this style, IAsyncEnumerable is not controled in UniTask).\npublic async IAsyncEnumerable\u003cint\u003e MyEveryUpdate([EnumeratorCancellation]CancellationToken cancelationToken = default)\n{\n    var frameCount = 0;\n    await UniTask.Yield();\n    while (!token.IsCancellationRequested)\n    {\n        yield return frameCount++;\n        await UniTask.Yield();\n    }\n}\n\n// UniTaskAsyncEnumerable.Create and use `await writer.YieldAsync` instead of `yield return`.\npublic IUniTaskAsyncEnumerable\u003cint\u003e MyEveryUpdate()\n{\n    // writer(IAsyncWriter\u003cT\u003e) has `YieldAsync(value)` method.\n    return UniTaskAsyncEnumerable.Create\u003cint\u003e(async (writer, token) =\u003e\n    {\n        var frameCount = 0;\n        await UniTask.Yield();\n        while (!token.IsCancellationRequested)\n        {\n            await writer.YieldAsync(frameCount++); // instead of `yield return`\n            await UniTask.Yield();\n        }\n    });\n}\n```\n\nAwaitable Events\n---\nAll uGUI component implements `***AsAsyncEnumerable` to convert asynchronous streams of events.\n\n```csharp\nasync UniTask TripleClick()\n{\n    // In default, used button.GetCancellationTokenOnDestroy to manage lieftime of async\n    await button.OnClickAsync();\n    await button.OnClickAsync();\n    await button.OnClickAsync();\n    Debug.Log(\"Three times clicked\");\n}\n\n// more efficient way\nasync UniTask TripleClick()\n{\n    using (var handler = button.GetAsyncClickEventHandler())\n    {\n        await handler.OnClickAsync();\n        await handler.OnClickAsync();\n        await handler.OnClickAsync();\n        Debug.Log(\"Three times clicked\");\n    }\n}\n\n// use async LINQ\nasync UniTask TripleClick(CancellationToken token)\n{\n    await button.OnClickAsAsyncEnumerable().Take(3).Last();\n    Debug.Log(\"Three times clicked\");\n}\n\n// use async LINQ2\nasync UniTask TripleClick(CancellationToken token)\n{\n    await button.OnClickAsAsyncEnumerable().Take(3).ForEachAsync(_ =\u003e\n    {\n        Debug.Log(\"Every clicked\");\n    });\n    Debug.Log(\"Three times clicked, complete.\");\n}\n```\n\nAll MonoBehaviour message events can convert async-streams by `AsyncTriggers` that can be enabled by `using Cysharp.Threading.Tasks.Triggers;`. AsyncTrigger can be created using `GetAsync***Trigger` and triggers itself as UniTaskAsyncEnumerable.\n\n```csharp\nvar trigger = this.GetOnCollisionEnterAsyncHandler();\nawait trigger.OnCollisionEnterAsync();\nawait trigger.OnCollisionEnterAsync();\nawait trigger.OnCollisionEnterAsync();\n\n// every moves.\nawait this.GetAsyncMoveTrigger().ForEachAsync(axisEventData =\u003e\n{\n});\n```\n\n`AsyncReactiveProperty`, `AsyncReadOnlyReactiveProperty` is UniTask's version of ReactiveProperty. `BindTo` extension method of `IUniTaskAsyncEnumerable\u003cT\u003e` for binding asynchronous stream values to Unity components(Text/Selectable/TMP/Text).\n\n```csharp\nvar rp = new AsyncReactiveProperty\u003cint\u003e(99);\n\n// AsyncReactiveProperty itself is IUniTaskAsyncEnumerable, you can query by LINQ\nrp.ForEachAsync(x =\u003e\n{\n    Debug.Log(x);\n}, this.GetCancellationTokenOnDestroy()).Forget();\n\nrp.Value = 10; // push 10 to all subscriber\nrp.Value = 11; // push 11 to all subscriber\n\n// WithoutCurrent ignore initial value\n// BindTo bind stream value to unity components.\nrp.WithoutCurrent().BindTo(this.textComponent);\n\nawait rp.WaitAsync(); // wait until next value set\n\n// also exists ToReadOnlyAsyncReactiveProperty\nvar rp2 = new AsyncReactiveProperty\u003cint\u003e(99);\nvar rorp = rp.CombineLatest(rp2, (x, y) =\u003e (x, y)).ToReadOnlyAsyncReactiveProperty(CancellationToken.None);\n```\n\nA pull-type asynchronous stream does not get the next values until the asynchronous processing in the sequence is complete. This could spill data from push-type events such as buttons.\n\n```csharp\n// can not get click event during 3 seconds complete.\nawait button.OnClickAsAsyncEnumerable().ForEachAwaitAsync(async x =\u003e\n{\n    await UniTask.Delay(TimeSpan.FromSeconds(3));\n});\n```\n\nIt is useful (prevent double-click) but not useful sometimes.\n\nUsing the `Queue()` method will also queue events during asynchronous processing.\n\n```csharp\n// queued message in asynchronous processing\nawait button.OnClickAsAsyncEnumerable().Queue().ForEachAwaitAsync(async x =\u003e\n{\n    await UniTask.Delay(TimeSpan.FromSeconds(3));\n});\n```\n\nOr use `Subscribe`, fire and forget style.\n\n```csharp\nbutton.OnClickAsAsyncEnumerable().Subscribe(async x =\u003e\n{\n    await UniTask.Delay(TimeSpan.FromSeconds(3));\n});\n```\n\nChannel\n---\n`Channel` is the same as [System.Threading.Tasks.Channels](https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels?view=netcore-3.1) which is similar to a GoLang Channel.\n\nCurrently it only supports multiple-producer, single-consumer unbounded channels. It can create by `Channel.CreateSingleConsumerUnbounded\u003cT\u003e()`.\n\nFor 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.\n\n`ReadAllAsync` returns `IUniTaskAsyncEnumerable\u003cT\u003e` so query LINQ operators. Reader only allows single-consumer but uses `.Publish()` query operator to enable multicast message. For example, make pub/sub utility.\n\n```csharp\npublic class AsyncMessageBroker\u003cT\u003e : IDisposable\n{\n    Channel\u003cT\u003e channel;\n\n    IConnectableUniTaskAsyncEnumerable\u003cT\u003e multicastSource;\n    IDisposable connection;\n\n    public AsyncMessageBroker()\n    {\n        channel = Channel.CreateSingleConsumerUnbounded\u003cT\u003e();\n        multicastSource = channel.Reader.ReadAllAsync().Publish();\n        connection = multicastSource.Connect(); // Publish returns IConnectableUniTaskAsyncEnumerable.\n    }\n\n    public void Publish(T value)\n    {\n        channel.Writer.TryWrite(value);\n    }\n\n    public IUniTaskAsyncEnumerable\u003cT\u003e Subscribe()\n    {\n        return multicastSource;\n    }\n\n    public void Dispose()\n    {\n        channel.Writer.TryComplete();\n        connection.Dispose();\n    }\n}\n```\n\nvs Awaitable\n---\nUnity 6 introduces the awaitable type, [Awaitable](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Awaitable.html). To put it simply, Awaitable can be considered a subset of UniTask, and in fact, Awaitable's design was influenced by UniTask. It should be able to handle PlayerLoop-based awaits, pooled Tasks, and support for cancellation with `CancellationToken` in a similar way. With its inclusion in the standard library, you may wonder whether to continue using UniTask or migrate to Awaitable. Here's a brief guide.\n\nFirst, the functionality provided by Awaitable is equivalent to what coroutines offer. Instead of `yield return`, you use await; `await NextFrameAsync()` replaces `yield return null`; and there are equivalents for `WaitForSeconds` and `EndOfFrame`. However, that's the extent of it. Being coroutine-based in terms of functionality, it lacks Task-based features. In practical application development using async/await, operations like `WhenAll` are essential. Additionally, UniTask enables many frame-based operations (such as `DelayFrame`) and more flexible PlayerLoopTiming control, which are not available in Awaitable. Of course, there's no Tracker Window either.\n\nTherefore, I recommend using UniTask for application development. UniTask is a superset of Awaitable and includes many essential features. For library development, where you want to avoid external dependencies, using Awaitable as a return type for methods would be appropriate. Awaitable can be converted to UniTask using `AsUniTask`, so there's no issue in handling Awaitable-based functionality within the UniTask library. Of course, if you don't need to worry about dependencies, using UniTask would be the best choice even for library development.\n\nFor Unit Testing\n---\nUnity's `[UnityTest]` attribute can test coroutine(IEnumerator) but can not test async. `UniTask.ToCoroutine` bridges async/await to coroutine so you can test async methods.\n\n```csharp\n[UnityTest]\npublic IEnumerator DelayIgnore() =\u003e UniTask.ToCoroutine(async () =\u003e\n{\n    var time = Time.realtimeSinceStartup;\n\n    Time.timeScale = 0.5f;\n    try\n    {\n        await UniTask.Delay(TimeSpan.FromSeconds(3), ignoreTimeScale: true);\n\n        var elapsed = Time.realtimeSinceStartup - time;\n        Assert.AreEqual(3, (int)Math.Round(TimeSpan.FromSeconds(elapsed).TotalSeconds, MidpointRounding.ToEven));\n    }\n    finally\n    {\n        Time.timeScale = 1.0f;\n    }\n});\n```\n\nUniTask's own unit tests are written using Unity Test Runner and [Cysharp/RuntimeUnitTestToolkit](https://github.com/Cysharp/RuntimeUnitTestToolkit) to integrate with CI and check if IL2CPP is working.\n\nThreadPool limitation\n---\nMost UniTask methods run on a single thread (PlayerLoop), with only `UniTask.Run`(`Task.Run` equivalent) and `UniTask.SwitchToThreadPool` running on a thread pool. If you use a thread pool, it won't work with WebGL and so on.\n\n`UniTask.Run` is now deprecated. You can use `UniTask.RunOnThreadPool` instead. And also consider whether you can use `UniTask.Create` or `UniTask.Void`.\n\nIEnumerator.ToUniTask limitation\n---\nYou can convert coroutine(IEnumerator) to UniTask(or await directly) but it has some limitations.\n\n* `WaitForEndOfFrame`/`WaitForFixedUpdate`/`Coroutine` is not supported.\n* Consuming loop timing is not the same as `StartCoroutine`, it uses the specified `PlayerLoopTiming` and the default `PlayerLoopTiming.Update` is run before MonoBehaviour's `Update` and `StartCoroutine`'s loop.\n\nIf you want fully compatible conversion from coroutine to async, use the `IEnumerator.ToUniTask(MonoBehaviour coroutineRunner)` overload. It executes StartCoroutine on an instance of the argument MonoBehaviour and waits for it to complete in UniTask.\n\nFor UnityEditor\n---\nUniTask can run on Unity Editor like an Editor Coroutine. However, there are some limitations.\n\n* UniTask.Delay's DelayType.DeltaTime, UnscaledDeltaTime do not work correctly because they can not get deltaTime in editor. Therefore run on EditMode, automatically change DelayType to `DelayType.Realtime` that wait for the right time.\n* All PlayerLoopTiming run on the timing `EditorApplication.update`.\n* `-batchmode` with `-quit` does not work because Unity does not run `EditorApplication.update` and quit after a single frame. Instead, don't use `-quit` and quit manually with `EditorApplication.Exit(0)`.\n\nCompare with Standard Task API\n---\nUniTask has many standard Task-like APIs. This table shows what the alternative apis are.\n\nUse standard type.\n\n| .NET Type | UniTask Type | \n| --- | --- |\n| `IProgress\u003cT\u003e` | --- |\n| `CancellationToken` | --- | \n| `CancellationTokenSource` | --- |\n\nUse UniTask type.\n\n| .NET Type | UniTask Type | \n| --- | --- |\n| `Task`/`ValueTask` | `UniTask` |\n| `Task\u003cT\u003e`/`ValueTask\u003cT\u003e` | `UniTask\u003cT\u003e` |\n| `async void` | `async UniTaskVoid` | \n| `+= async () =\u003e { }` | `UniTask.Void`, `UniTask.Action`, `UniTask.UnityAction` |\n| --- | `UniTaskCompletionSource` |\n| `TaskCompletionSource\u003cT\u003e` | `UniTaskCompletionSource\u003cT\u003e`/`AutoResetUniTaskCompletionSource\u003cT\u003e` |\n| `ManualResetValueTaskSourceCore\u003cT\u003e` | `UniTaskCompletionSourceCore\u003cT\u003e` |\n| `IValueTaskSource` | `IUniTaskSource` |\n| `IValueTaskSource\u003cT\u003e` | `IUniTaskSource\u003cT\u003e` |\n| `ValueTask.IsCompleted` | `UniTask.Status.IsCompleted()` |\n| `ValueTask\u003cT\u003e.IsCompleted` | `UniTask\u003cT\u003e.Status.IsCompleted()` |\n| `new Progress\u003cT\u003e` | `Progress.Create\u003cT\u003e` |\n| `CancellationToken.Register(UnsafeRegister)` | `CancellationToken.RegisterWithoutCaptureExecutionContext` |\n| `CancellationTokenSource.CancelAfter` | `CancellationTokenSource.CancelAfterSlim` |\n| `Channel.CreateUnbounded\u003cT\u003e(false){ SingleReader = true }` | `Channel.CreateSingleConsumerUnbounded\u003cT\u003e` |\n| `IAsyncEnumerable\u003cT\u003e` | `IUniTaskAsyncEnumerable\u003cT\u003e` |\n| `IAsyncEnumerator\u003cT\u003e` | `IUniTaskAsyncEnumerator\u003cT\u003e` |\n| `IAsyncDisposable` | `IUniTaskAsyncDisposable` |\n| `Task.Delay` | `UniTask.Delay` |\n| `Task.Yield` | `UniTask.Yield` |\n| `Task.Run` | `UniTask.RunOnThreadPool` |\n| `Task.WhenAll` | `UniTask.WhenAll` |\n| `Task.WhenAny` | `UniTask.WhenAny` |\n| `Task.WhenEach` | `UniTask.WhenEach` |\n| `Task.CompletedTask` | `UniTask.CompletedTask` |\n| `Task.FromException` | `UniTask.FromException` |\n| `Task.FromResult` | `UniTask.FromResult` |\n| `Task.FromCanceled` | `UniTask.FromCanceled` |\n| `Task.ContinueWith` | `UniTask.ContinueWith` |\n| `TaskScheduler.UnobservedTaskException` | `UniTaskScheduler.UnobservedTaskException` |\n\nPooling Configuration\n---\nUniTask aggressively caches async promise objects to achieve zero allocation (for technical details, see blog post [UniTask v2 — Zero Allocation async/await for Unity, with Asynchronous LINQ](https://medium.com/@neuecc/unitask-v2-zero-allocation-async-await-for-unity-with-asynchronous-linq-1aa9c96aa7dd)). By default, it caches all promises but you can configure `TaskPool.SetMaxPoolSize` to your value, the value indicates cache size per type. `TaskPool.GetCacheSizeInfo` returns currently cached objects in pool.\n\n```csharp\nforeach (var (type, size) in TaskPool.GetCacheSizeInfo())\n{\n    Debug.Log(type + \":\" + size);\n}\n```\n\nAllocation on Profiler\n---\nIn UnityEditor the profiler shows allocation of compiler generated AsyncStateMachine but it only occurs in debug(development) build. C# Compiler generates AsyncStateMachine as class on Debug build and as struct on Release build.\n\nUnity supports Code Optimization option starting in 2020.1 (right, footer).\n\n![](https://user-images.githubusercontent.com/46207/89967342-2f944600-dc8c-11ea-99fc-0b74527a16f6.png)\n\nYou can change C# compiler optimization to release to remove AsyncStateMachine allocation in development builds. This optimization option can also be set via `Compilation.CompilationPipeline-codeOptimization`, and `Compilation.CodeOptimization`.\n\nUniTaskSynchronizationContext\n---\nUnity's default SynchronizationContext(`UnitySynchronizationContext`) is a poor implementation for performance. UniTask bypasses `SynchronizationContext`(and `ExecutionContext`) so it does not use it but if exists in `async Task`, still used it. `UniTaskSynchronizationContext` is a replacement of `UnitySynchronizationContext` which is better for performance.\n\n```csharp\npublic class SyncContextInjecter\n{\n    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]\n    public static void Inject()\n    {\n        SynchronizationContext.SetSynchronizationContext(new UniTaskSynchronizationContext());\n    }\n}\n```\n\nThis is an optional choice and is not always recommended; `UniTaskSynchronizationContext` is less performant than `async UniTask` and is not a complete UniTask replacement. It also does not guarantee full behavioral compatibility with the `UnitySynchronizationContext`.\n\nAPI References\n---\nUniTask's API References are hosted at [cysharp.github.io/UniTask](https://cysharp.github.io/UniTask/api/Cysharp.Threading.Tasks.html) by [DocFX](https://dotnet.github.io/docfx/) and [Cysharp/DocfXTemplate](https://github.com/Cysharp/DocfxTemplate).\n\nFor example, UniTask's factory methods can be seen at [UniTask#methods](https://cysharp.github.io/UniTask/api/Cysharp.Threading.Tasks.UniTask.html#methods-1). UniTaskAsyncEnumerable's factory/extension methods can be seen at [UniTaskAsyncEnumerable#methods](https://cysharp.github.io/UniTask/api/Cysharp.Threading.Tasks.Linq.UniTaskAsyncEnumerable.html#methods-1).\n\nUPM Package\n---\n### Install via git URL\n\nRequires a version of unity that supports path query parameter for git packages (Unity \u003e= 2019.3.4f1, Unity \u003e= 2020.1a21). You can add `https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask` to Package Manager\n\n![image](https://user-images.githubusercontent.com/46207/79450714-3aadd100-8020-11ea-8aae-b8d87fc4d7be.png)\n\n![image](https://user-images.githubusercontent.com/46207/83702872-e0f17c80-a648-11ea-8183-7469dcd4f810.png)\n\nor add `\"com.cysharp.unitask\": \"https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask\"` to `Packages/manifest.json`.\n\nIf you want to set a target version, UniTask uses the `*.*.*` release tag so you can specify a version like `#2.1.0`. For example `https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.1.0`.\n\n\n.NET Core\n---\nFor .NET Core, use NuGet.\n\n\u003e PM\u003e Install-Package [UniTask](https://www.nuget.org/packages/UniTask)\n\nUniTask of .NET Core version is a subset of Unity UniTask with PlayerLoop dependent methods removed.\n\nIt runs at higher performance than the standard Task/ValueTask, but you should be careful to ignore the ExecutionContext/SynchronizationContext when using it. `AsyncLocal` also does not work because it ignores ExecutionContext.\n\nIf you use UniTask internally, but provide ValueTask as an external API, you can write it like the following(Inspired by [PooledAwait](https://github.com/mgravell/PooledAwait)).\n\n```csharp\npublic class ZeroAllocAsyncAwaitInDotNetCore\n{\n    public ValueTask\u003cint\u003e DoAsync(int x, int y)\n    {\n        return Core(this, x, y);\n\n        static async UniTask\u003cint\u003e Core(ZeroAllocAsyncAwaitInDotNetCore self, int x, int y)\n        {\n            // do anything...\n            await Task.Delay(TimeSpan.FromSeconds(x + y));\n            await UniTask.Yield();\n\n            return 10;\n        }\n    }\n}\n\n// UniTask does not return to original SynchronizationContext but you can use helper `ReturnToCurrentSynchronizationContext`.\npublic ValueTask TestAsync()\n{\n    await using (UniTask.ReturnToCurrentSynchronizationContext())\n    {\n        await UniTask.SwitchToThreadPool();\n        // do anything..\n    }\n}\n```\n\n.NET Core version is intended to allow users to use UniTask as an interface when sharing code with Unity (such as [Cysharp/MagicOnion](https://github.com/Cysharp/MagicOnion/)). .NET Core version of UniTask enables smooth code sharing.\n\nUtility methods such as WhenAll which are equivalent to UniTask are provided as [Cysharp/ValueTaskSupplement](https://github.com/Cysharp/ValueTaskSupplement).\n\nLicense\n---\nThis library is under the MIT License.\n","funding_links":["https://github.com/sponsors/neuecc"],"categories":["C\\#","C#","Uncategorized","Async / Await"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FCysharp%2FUniTask","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FCysharp%2FUniTask","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FCysharp%2FUniTask/lists"}