mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-03-22 10:34:30 +08:00
- 添加协程上下文、句柄、调度器和作用域管理类 - 实现协程等待指令包括 WaitForSeconds、WaitUntil 和 WaitWhile - 创建协程系统和全局协程作用域管理器 - 定义协程相关抽象接口 ICoroutineScheduler、ICoroutineScope 等 - 升级 Meziantou.Analyzer 依赖版本至 2.0.283 - 升级 Meziantou.Polyfill 依赖版本至 1.0.100
57 lines
1.7 KiB
C#
57 lines
1.7 KiB
C#
using System.Collections;
|
|
using GFramework.Game.Abstractions.coroutine;
|
|
|
|
namespace GFramework.Game.coroutine;
|
|
|
|
public class CoroutineScope : ICoroutineScope, IDisposable
|
|
{
|
|
private readonly List<CoroutineScope> _children = new();
|
|
private readonly CoroutineScope _parent;
|
|
private readonly HashSet<CoroutineHandle> _runningCoroutines = new();
|
|
private readonly CoroutineScheduler _scheduler;
|
|
|
|
private bool _isActive = true;
|
|
|
|
public CoroutineScope(CoroutineScheduler scheduler, string name = null, CoroutineScope parent = null)
|
|
{
|
|
_scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
|
|
_parent = parent;
|
|
_parent?._children.Add(this);
|
|
Name = name ?? $"Scope_{GetHashCode()}";
|
|
}
|
|
|
|
public string Name { get; }
|
|
public bool IsActive => _isActive;
|
|
|
|
public void Cancel()
|
|
{
|
|
if (!_isActive) return;
|
|
|
|
_isActive = false;
|
|
|
|
foreach (var child in _children.ToList())
|
|
child.Cancel();
|
|
|
|
foreach (var handle in _runningCoroutines.ToList())
|
|
handle.Cancel();
|
|
|
|
_runningCoroutines.Clear();
|
|
}
|
|
|
|
public void Dispose() => Cancel();
|
|
|
|
public CoroutineHandle Launch(IEnumerator routine)
|
|
{
|
|
if (!_isActive)
|
|
throw new InvalidOperationException($"Scope '{Name}' is not active");
|
|
|
|
var context = new CoroutineContext(this, _scheduler, this);
|
|
var handle = _scheduler.StartCoroutine(routine, context);
|
|
|
|
_runningCoroutines.Add(handle);
|
|
handle.OnComplete += () => _runningCoroutines.Remove(handle);
|
|
handle.OnError += (ex) => _runningCoroutines.Remove(handle);
|
|
|
|
return handle;
|
|
}
|
|
} |