Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
MIT License
Copyright (c) 2019 Yoshitaka Kimisaki
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.Collections.Concurrent;
using System.Threading;
using UniRx;
using UniRx.Async;
namespace Tonari.Unity
{
public class SequentialProcessQueue : IDisposable
{
private ReactiveProperty<bool> isProcessing;
public IReadOnlyReactiveProperty<bool> IsProcessing => isProcessing;
private struct Inner
{
public Func<UniTask> Task;
public CancellationToken Cancellation;
}
private ConcurrentQueue<Inner> queue;
private Func<UniTask> current;
private IDisposable loopSubscription;
private IObservable<long> loopDispatcher;
private CancellationTokenSource allQueueCancellation;
public CancellationToken AllQueueCancellation => allQueueCancellation.Token;
private bool isAlreadyDisposed;
public SequentialProcessQueue(MainThreadDispatchType mainThreadDispatchType = MainThreadDispatchType.Update)
{
isProcessing = new ReactiveProperty<bool>();
queue = new ConcurrentQueue<Inner>();
switch (mainThreadDispatchType)
{
case MainThreadDispatchType.EndOfFrame:
loopDispatcher = Observable.EveryEndOfFrame();
break;
case MainThreadDispatchType.FixedUpdate:
loopDispatcher = Observable.EveryFixedUpdate();
break;
case MainThreadDispatchType.GameObjectUpdate:
loopDispatcher = Observable.EveryGameObjectUpdate();
break;
case MainThreadDispatchType.LateUpdate:
loopDispatcher = Observable.EveryLateUpdate();
break;
case MainThreadDispatchType.Update:
default:
loopDispatcher = Observable.EveryUpdate();
break;
}
allQueueCancellation = new CancellationTokenSource();
}
public void Dispose()
{
if (isAlreadyDisposed)
{
return;
}
isAlreadyDisposed = true;
allQueueCancellation.Cancel();
if (isProcessing.Value)
{
isProcessing.SetValueAndForceNotify(false);
}
isProcessing.Dispose();
loopSubscription?.Dispose();
queue = null;
}
public void ReserveProcess(Func<UniTask> process, CancellationToken cancellation = default)
{
if (isAlreadyDisposed)
{
throw new OperationCanceledException("UniSequentialQueue is already disposed.", allQueueCancellation.Token);
}
if (cancellation.IsCancellationRequested)
{
throw new OperationCanceledException("Request process is already cancelled;.", cancellation);
}
queue.Enqueue(new Inner { Task = process, Cancellation = cancellation });
if (loopSubscription == null)
{
loopSubscription = loopDispatcher.Subscribe(_ => ProcessFrame());
}
}
private void ProcessFrame()
{
if (isAlreadyDisposed)
{
return;
}
if (current != null)
{
return;
}
Dequeue:
if (queue.IsEmpty)
{
if (isProcessing.Value)
{
isProcessing.SetValueAndForceNotify(false);
}
return;
}
if (queue.TryDequeue(out var inner))
{
if (inner.Cancellation.IsCancellationRequested)
{
goto Dequeue; // 次のフレームを待たないためにgoto
}
ProcessInner(inner);
}
}
private void ProcessInner(Inner inner)
{
current = inner.Task;
if (!isProcessing.Value)
{
isProcessing.SetValueAndForceNotify(true);
}
void @finally()
{
if (isAlreadyDisposed || current == null)
{
return;
}
current = null;
if (queue.IsEmpty)
{
isProcessing.SetValueAndForceNotify(false);
}
}
inner.Task()
.ContinueWith(() => @finally())
.Forget(_ => @finally());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.