Skip to content

Instantly share code, notes, and snippets.

@sfider
Last active December 5, 2024 12:07
Show Gist options
  • Save sfider/d7b71107cb6b58040075806bd54ef900 to your computer and use it in GitHub Desktop.
Save sfider/d7b71107cb6b58040075806bd54ef900 to your computer and use it in GitHub Desktop.
UniTaskPause is an object you can await on in your async task until someone calls UnPause()
/*
* Copyright 2024 Marcin Swiderski
*
* The MIT Licence (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Runtime.CompilerServices;
public class UniTaskPause
{
private Action _paused;
public bool IsPaused()
{
return _paused != null;
}
public void UnPause()
{
_paused?.Invoke();
_paused = null;
}
public Awaiter GetAwaiter()
{
return new Awaiter(this);
}
public readonly struct Awaiter : ICriticalNotifyCompletion
{
private readonly UniTaskPause _pause;
public Awaiter(UniTaskPause pause)
{
_pause = pause;
}
public bool IsCompleted => false;
public void GetResult() {}
public void OnCompleted(Action continuation)
{
_pause._paused = continuation;
}
public void UnsafeOnCompleted(Action continuation)
{
_pause._paused = continuation;
}
}
}
using System.Threading;
using Cysharp.Threading.Tasks;
using UnityEngine;
public class UniTaskPauseExampleUsage : MonoBehaviour
{
private UniTaskPause _workPause = new();
private void Start()
{
_ = WorkUpdate(destroyCancellationToken);
}
private async UniTaskVoid WorkUpdate(CancellationToken cancel)
{
while (true) {
await UniTask.Yield(cancel);
// Do some work
bool moreWork = false;
if (!moreWork) {
await _workPause;
}
}
}
private void OnMoreWork()
{
_workPause.UnPause();
}
}
@sfider
Copy link
Author

sfider commented Dec 1, 2024

It's not really tied to UniTask in any way, but I made it with the intent of using it with UniTask.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment