├── CoEvent └── Runtime │ ├── Async │ ├── Interface │ │ ├── ICoTask.cs │ │ ├── IAuthorization.cs │ │ ├── IAsyncTokenProperty.cs │ │ ├── ICriticalAwaiter.cs │ │ ├── IAwaitable.cs │ │ ├── IAsyncTask.cs │ │ └── IAwaiter.cs │ ├── UnitySupport │ │ ├── DoTweenSupport │ │ │ └── DoTweenSupport.cs │ │ ├── UnityCoroutineSupport │ │ │ └── CoroutineToCoTask.cs │ │ ├── AddressableSupport │ │ │ └── AddressableEx.cs │ │ └── UnityAsyncOperation │ │ │ └── AsyncOperationEx.cs │ ├── Ex │ │ ├── CoTaskToCoroutine.cs │ │ ├── CoTask_Ex.cs │ │ └── CoTask.Await.cs │ ├── AsyncTreeTokenNode.cs │ ├── AsyncToken.cs │ ├── CounterCall.cs │ ├── CoTaskBuilder.cs │ └── CoTask.cs │ ├── Event │ ├── ICoVarOperator.cs │ ├── CoUnsafeAs.cs │ ├── Extensions_Operator.cs │ ├── CoOperator.cs │ ├── ICoEventBase.cs │ ├── Extensions_Send.cs │ ├── Extensions_Condition.cs │ ├── Extensions_Subscribe.cs │ ├── Extensions_Call.cs │ └── Extensions_UnSubscribe.cs │ ├── Life │ ├── ILifeCycle.cs │ └── CoEventPublisher.cs │ ├── CoEvent.Runtime.asmdef │ ├── Pool │ ├── IPool.cs │ └── CoDefaultPool.cs │ └── CoEvent.cs ├── Samples ├── CancelTest.cs ├── AsyncEventTest.cs ├── CoTask2CoroutineTest.cs ├── YieldTest.cs └── SyncEventTest.cs ├── .gitignore ├── README.md └── LICENSE /CoEvent/Runtime/Async/Interface/ICoTask.cs: -------------------------------------------------------------------------------- 1 | namespace CoEvents 2 | { 3 | public interface ICoTask 4 | { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/ICoVarOperator.cs: -------------------------------------------------------------------------------- 1 | namespace CoEvents 2 | { 3 | public interface ICoVarOperator 4 | { 5 | //禁止在这写任何内容!否则可能引发程序崩溃。 6 | } 7 | 8 | 9 | } 10 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Life/ILifeCycle.cs: -------------------------------------------------------------------------------- 1 | namespace CoEvents 2 | { 3 | public interface IUpdate : ISendEvent { }; 4 | 5 | public interface IFixedUpdate : ISendEvent { } 6 | 7 | public interface ILateUpdate : ISendEvent { } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Interface/IAuthorization.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.1.13 4 | * Description : 5 | * 实现该接口以获取有效授权 6 | */ 7 | 8 | namespace CoEvents.Async 9 | { 10 | 11 | public interface IAuthorization 12 | { 13 | bool Authorization { get; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CoEvent/Runtime/CoEvent.Runtime.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "CoEvent.Runtime", 3 | "rootNamespace": "CoEvents", 4 | "references": [], 5 | "includePlatforms": [], 6 | "excludePlatforms": [], 7 | "allowUnsafeCode": true, 8 | "overrideReferences": false, 9 | "precompiledReferences": [], 10 | "autoReferenced": true, 11 | "defineConstraints": [], 12 | "versionDefines": [], 13 | "noEngineReferences": false 14 | } -------------------------------------------------------------------------------- /CoEvent/Runtime/Pool/IPool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CoEvents 4 | { 5 | public interface IPool 6 | { 7 | public object Allocate(Type type); 8 | public void Recycle(Type type, object item); 9 | 10 | public T Allocate() 11 | { 12 | return (T)Allocate(typeof(T)); 13 | } 14 | public void Recycle(object item) 15 | { 16 | Recycle(typeof(T), item); 17 | } 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Life/CoEventPublisher.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace CoEvents 4 | { 5 | public class CoEventPublisher : MonoBehaviour 6 | { 7 | 8 | void FixedUpdate() 9 | { 10 | this.Operator().Send(); 11 | } 12 | void Update() 13 | { 14 | this.Operator().Send(Time.deltaTime); 15 | } 16 | 17 | void LateUpdate() 18 | { 19 | this.Operator().Send(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Samples/CancelTest.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Async; 2 | using UnityEngine; 3 | 4 | public class CancelTest : MonoBehaviour 5 | { 6 | 7 | public async CoTask DoTimeLog() 8 | { 9 | 10 | 11 | await CoTask.Delay(5); 12 | Debug.Log("End"); 13 | } 14 | 15 | 16 | 17 | 18 | void Start() 19 | { 20 | 21 | DoTimeLog().WithToken(out var token); 22 | 23 | token.OnCanceled += () => 24 | { 25 | Debug.Log($"{nameof(CancelTest)}."); 26 | }; 27 | token.Cancel(); 28 | 29 | } 30 | 31 | 32 | } 33 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/CoUnsafeAs.cs: -------------------------------------------------------------------------------- 1 | using Unity.Collections.LowLevel.Unsafe; 2 | namespace CoEvents 3 | { 4 | //在这里决定强转的方法实现 5 | 6 | internal static class CoUnsafeAs 7 | { 8 | //[DebuggerHidden] 9 | internal static TTo As(ref TFrom t) 10 | { 11 | #if UNITY_2020_1_OR_NEWER 12 | return UnsafeUtility.As(ref t); 13 | #elif NETCORE 14 | return Unsafe.As(ref t); 15 | #else 16 | 17 | #error Unsupported platform!(请手动实现Unsafe.As或切换到支持的平台上) 18 | 19 | #endif 20 | } 21 | 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Interface/IAsyncTokenProperty.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 创建IAsyncTokenProperty接口来对接异步令牌需要的属性和方法,就是提供一个对接口,仅此而已 6 | */ 7 | 8 | namespace CoEvents.Async.Internal 9 | { 10 | /// 11 | /// 使用该接口统一支持异步令牌 12 | /// 13 | public interface IAsyncTokenProperty 14 | { 15 | AsyncTreeTokenNode Token { get; internal set; } 16 | 17 | public void SetCancel(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Samples/AsyncEventTest.cs: -------------------------------------------------------------------------------- 1 | using CoEvents; 2 | using CoEvents.Async; 3 | using UnityEngine; 4 | 5 | 6 | 7 | public interface IAsyncEvent : ICallEvent { } 8 | public class AsyncEventTest : MonoBehaviour 9 | { 10 | 11 | public async CoTask DoAsync(int x) 12 | { 13 | //等待X秒 14 | await CoTask.Delay(x); 15 | Debug.Log("hha"); 16 | } 17 | 18 | 19 | async void Start() 20 | { 21 | //注册事件 22 | this.Operator().Subscribe(DoAsync); 23 | 24 | //调用第一个注册的事件 25 | await this.Operator().CallFirst(2); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Samples/CoTask2CoroutineTest.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Async; 2 | using System.Collections; 3 | using UnityEngine; 4 | 5 | public class CoTask2Coroutine : MonoBehaviour 6 | { 7 | public async CoTask DoAsync() 8 | { 9 | await CoTask.Delay(5); 10 | Debug.Log("hh"); 11 | } 12 | void Start() 13 | { 14 | IEnumerator enumerator = CoTask.ToCoroutine(DoAsync); 15 | StartCoroutine(enumerator); 16 | 17 | 18 | StartCoroutine(CoTask.ToCoroutine(async () => 19 | { 20 | await CoTask.Delay(5); 21 | Debug.Log("hh2"); 22 | })); 23 | 24 | 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/UnitySupport/DoTweenSupport/DoTweenSupport.cs: -------------------------------------------------------------------------------- 1 | 2 | //打开这行注释以支持DoTween完成的等待 3 | 4 | //#define CoEvent_Async_DoTween_Enable 5 | 6 | #if CoEvent_Async_DoTween_Enable 7 | 8 | namespace CoEvents.Async 9 | { 10 | public static class DoTweenSupport 11 | { 12 | /// 13 | /// 有一定的GC分配,慎用 14 | /// 15 | /// 16 | /// 17 | public static CoTask GetAwaiter(this DG.Tweening.Tween tween) 18 | { 19 | var task = CoTask.Create(); 20 | tween.onComplete+=()=>task.SetResult(); 21 | return task; 22 | } 23 | } 24 | } 25 | #endif -------------------------------------------------------------------------------- /Samples/YieldTest.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Async; 2 | using UnityEngine; 3 | 4 | public class YieldTest : MonoBehaviour 5 | { 6 | 7 | //测试方法 8 | public async CoTask Test() 9 | { 10 | //延迟5秒输出 11 | await CoTask.Delay(5f); 12 | Debug.Log(11); 13 | } 14 | 15 | //测试流程 16 | public async CoTask DealyTimePause() 17 | { 18 | //取得令牌 19 | Test().WithToken(out var token).Discard(); 20 | //三秒后暂停 21 | await CoTask.Delay(3); 22 | Debug.Log("暂停"); 23 | token.Yield(); 24 | //五秒后继续 25 | await CoTask.Delay(5); 26 | token.Continue(); 27 | } 28 | 29 | void Start() 30 | { 31 | DealyTimePause().Discard(); 32 | } 33 | 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Interface/ICriticalAwaiter.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 在IAwairer的基础上,我们创建ICriticalAwaiter,能够使得Awaiter可以处理异常 6 | */ 7 | 8 | 9 | using System.Runtime.CompilerServices; 10 | namespace CoEvents.Async 11 | { 12 | /// 13 | /// 实现可以被GetAwaiter返回支持的Awaiter对象(当执行代码可能给程序造成负面影响时) 14 | /// 15 | public interface ICriticalAwaiter : ICriticalNotifyCompletion, IAwaiter 16 | { 17 | 18 | } 19 | 20 | /// 21 | /// 实现可以被GetAwaiter返回支持的Awaiter对象(当执行代码可能给程序造成负面影响时) 22 | /// 23 | public interface ICriticalAwaiter : ICriticalNotifyCompletion, IAwaiter 24 | { 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/UnitySupport/UnityCoroutineSupport/CoroutineToCoTask.cs: -------------------------------------------------------------------------------- 1 | 2 | //打开这行注释以支持CoTask与协程的转换 3 | #define CoEvent_Async_CoTask2Coroutine_Enable 4 | 5 | 6 | 7 | #if CoEvent_Async_CoTask2Coroutine_Enable 8 | 9 | using System.Collections; 10 | using System.Diagnostics; 11 | using System.Runtime.CompilerServices; 12 | 13 | namespace CoEvents.Async 14 | { 15 | public static class CoTask2Coroutine 16 | { 17 | 18 | 19 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 20 | public static CoTask GetAwaiter(this IEnumerator enumerator) 21 | { 22 | CoTask task = CoTask.Create(); 23 | IEnumerator Temp() 24 | { 25 | yield return enumerator; 26 | if (task.Token.Authorization) 27 | task.SetResult(); 28 | } 29 | 30 | CoEvent.Mono.StartCoroutine(Temp()); 31 | return task; 32 | } 33 | 34 | } 35 | } 36 | #endif -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Ex/CoTaskToCoroutine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Runtime.CompilerServices; 6 | 7 | namespace CoEvents.Async 8 | { 9 | public partial class CoTask 10 | { 11 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 12 | public static IEnumerator ToCoroutine(Func method) 13 | { 14 | if (method == null) throw new ArgumentNullException("method null "); 15 | CoTask task = method(); 16 | while (!task.IsCompleted) yield return null; 17 | } 18 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 19 | public static IEnumerator ToCoroutine(Func> method) 20 | { 21 | if (method == null) throw new ArgumentNullException("method null "); 22 | CoTask task = method(); 23 | while (!task.IsCompleted) yield return default; 24 | } 25 | 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/UnitySupport/AddressableSupport/AddressableEx.cs: -------------------------------------------------------------------------------- 1 | 2 | //打开下面这行注释即可支持Addressable操作完成的等待 3 | 4 | //#define CoEvent_Addressable_Enable 5 | 6 | #if CoEvent_Async_Addressable_Enable 7 | using System.Collections; 8 | using System.Collections.Generic; 9 | using System.ComponentModel; 10 | using UnityEngine; 11 | 12 | 13 | using UnityEngine.AddressableAssets; 14 | using UnityEngine.ResourceManagement.AsyncOperations; 15 | 16 | namespace CoEvents.Async 17 | { 18 | public static class AddressableEx 19 | { 20 | public static CoTask GetAwaiter(this AsyncOperationHandle handle) 21 | { 22 | var task = CoTask.Create(); 23 | handle.Completed += task.SetResult; 24 | return task; 25 | } 26 | public static CoTask> GetAwaiter(this AsyncOperationHandle handle) 27 | { 28 | var task = CoTask>.Create(); 29 | handle.Completed += task.SetResult; 30 | return task; 31 | } 32 | } 33 | 34 | } 35 | #endif -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/UnitySupport/UnityAsyncOperation/AsyncOperationEx.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | //打开这行注释以支持DoTween完成的等待 4 | 5 | #define CoEvent_Async_AsyncOperation_Enable 6 | 7 | #if CoEvent_Async_AsyncOperation_Enable 8 | 9 | using System; 10 | using UnityEngine; 11 | 12 | namespace CoEvents.Async 13 | { 14 | 15 | public static class AsyncOperationEx 16 | { 17 | public static CoTask GetAwaiter(this AsyncOperation operation) 18 | { 19 | var task = CoTask.Create(); 20 | operation.completed += task.SetResult; 21 | return task; 22 | 23 | } 24 | public static AsyncOperation WithProgress(this AsyncOperation operation, Action progress) 25 | { 26 | Action callback = (x) => 27 | { 28 | progress?.Invoke(operation.progress); 29 | }; 30 | operation.completed += (x) => 31 | { 32 | CoEvent.Instance.Operator().UnSubscribe(callback); 33 | }; 34 | CoEvent.Instance.Operator().Subscribe(callback); 35 | return operation; 36 | } 37 | 38 | 39 | 40 | } 41 | } 42 | #endif -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Interface/IAwaitable.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 为了使抽象的编辑器要求变得具体,这里创建接口统一可等待的对象 6 | */ 7 | 8 | namespace CoEvents.Async 9 | { 10 | /// 11 | /// 实现此接口使得一个对象可以被await关键字所支持 12 | /// 13 | /// 14 | /// 15 | public interface IAwaitable where TAwaiter : IAwaiter 16 | { 17 | /// 18 | /// 获取一个实现IAwaiter对象 19 | /// 20 | /// 21 | TAwaiter GetAwaiter(); 22 | } 23 | /// 24 | /// 实现此接口使得一个对象可以被await关键字所支持 25 | /// 26 | /// 27 | /// 28 | public interface IAwaitable where TAwaiter : IAwaiter 29 | { 30 | /// 31 | /// 获取一个实现IAwaiter对象 32 | /// 33 | /// 34 | TAwaiter GetAwaiter(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/Extensions_Operator.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Internal; 2 | using System; 3 | 4 | namespace CoEvents 5 | { 6 | public static class CoEventManagerEx1 7 | { 8 | //[DebuggerHidden] 9 | public static ICoVarOperator Operator(this object cov) where EventType : ISendEventBase 10 | { 11 | Type type = typeof(EventType); 12 | if (!CoEvent.container.ContainsKey(type)) CoEvent.container.Add(type, new CoOperator()); 13 | CoOperator cop = CoEvent.container[type]; 14 | return CoUnsafeAs.As, CoOperator>(ref cop); 15 | } 16 | } 17 | public static class CoEventManagerEx2 18 | { 19 | //[DebuggerHidden] 20 | public static ICoVarOperator Operator(this object cov) where EventType : ICallEventBase 21 | { 22 | Type type = typeof(EventType); 23 | if (!CoEvent.container.ContainsKey(type)) CoEvent.container.Add(type, new CoOperator()); 24 | CoOperator cop = CoEvent.container[type]; 25 | return CoUnsafeAs.As, CoOperator>(ref cop); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Interface/IAsyncTask.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 创建IAsyncTask来统一任务在awaiter标准以外的特殊行为 6 | */ 7 | 8 | 9 | using System; 10 | namespace CoEvents.Async 11 | { 12 | 13 | 14 | /// 15 | /// 异步任务接口 16 | /// 17 | public interface IAsyncTask : ICriticalAwaiter, ICoTask 18 | { 19 | /// 20 | /// 结束当前任务 21 | /// 22 | Action SetResult { get; } 23 | 24 | /// 25 | /// 当有异常时调用 26 | /// 27 | /// 28 | void SetException(Exception exception); 29 | 30 | 31 | } 32 | /// 33 | /// 异步任务接口 34 | /// 35 | /// 36 | public interface IAsyncTask : ICriticalAwaiter, ICoTask 37 | { 38 | /// 39 | /// 结束当前任务 40 | /// 41 | Action SetResult { get; } 42 | 43 | /// 44 | /// 当有异常时调用 45 | /// 46 | /// 47 | void SetException(Exception exception); 48 | 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Interface/IAwaiter.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 编译器Task-LIKE要求返回实现INotifyCompletion的对象,同时要求对象带有IsCompleted和GetResult 6 | * 这里实现这样的接口来约束返回对象的可行性 7 | */ 8 | 9 | using System.Runtime.CompilerServices; 10 | namespace CoEvents.Async 11 | { 12 | /// 13 | /// 实现可以被GetAwaiter返回支持的Awaiter对象 14 | /// 15 | public interface IAwaiter : INotifyCompletion 16 | { 17 | /// 18 | /// 获取一个状态,该状态表示正在异步等待的操作已经完成(成功完成或发生了异常);此状态会被编译器自动调用。 19 | /// 在实现中,为了达到各种效果,可以灵活应用其值:可以始终为 true,或者始终为 false。 20 | /// 21 | bool IsCompleted { get; set; } 22 | /// 23 | /// 此方法会被编译器在 await 结束时自动调用以获取返回值(包括异常)。 24 | /// 25 | void GetResult(); 26 | } 27 | 28 | /// 29 | /// 实现可以被GetAwaiter返回支持的Awaiter对象 30 | /// 31 | public interface IAwaiter : INotifyCompletion 32 | { 33 | /// 34 | /// 获取一个状态,该状态表示正在异步等待的操作已经完成(成功完成或发生了异常);此状态会被编译器自动调用。 35 | /// 在实现中,为了达到各种效果,可以灵活应用其值:可以始终为 true,或者始终为 false。 36 | /// 37 | bool IsCompleted { get; set; } 38 | 39 | /// 40 | /// 此方法会被编译器在 await 结束时自动调用以获取返回值(包括异常)。 41 | /// 42 | T GetResult(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # This .gitignore file should be placed at the root of your Unity project directory 2 | # 3 | # Get latest from https://github.com/github/gitignore/blob/main/Unity.gitignore 4 | # 5 | /[Ll]ibrary/ 6 | /[Tt]emp/ 7 | /[Oo]bj/ 8 | /[Bb]uild/ 9 | /[Bb]uilds/ 10 | /[Ll]ogs/ 11 | /[Tt]est/ 12 | /[Uu]ser[Ss]ettings/ 13 | 14 | # MemoryCaptures can get excessive in size. 15 | # They also could contain extremely sensitive data 16 | /[Mm]emoryCaptures/ 17 | 18 | # Recordings can get excessive in size 19 | /[Rr]ecordings/ 20 | 21 | # Uncomment this line if you wish to ignore the asset store tools plugin 22 | # /[Aa]ssets/AssetStoreTools* 23 | 24 | # Autogenerated Jetbrains Rider plugin 25 | /[Aa]ssets/Plugins/Editor/JetBrains* 26 | 27 | # Visual Studio cache directory 28 | .vs/ 29 | 30 | # Gradle cache directory 31 | .gradle/ 32 | 33 | # Autogenerated VS/MD/Consulo solution and project files 34 | ExportedObj/ 35 | .consulo/ 36 | *.csproj 37 | *.unityproj 38 | *.sln 39 | *.suo 40 | *.tmp 41 | *.user 42 | *.userprefs 43 | *.pidb 44 | *.booproj 45 | *.svd 46 | *.pdb 47 | *.mdb 48 | *.opendb 49 | *.VC.db 50 | *.meta 51 | # Unity3D generated meta files 52 | *.pidb.meta 53 | *.pdb.meta 54 | *.mdb.meta 55 | 56 | # Unity3D generated file on crash reports 57 | sysinfo.txt 58 | 59 | # Builds 60 | *.apk 61 | *.aab 62 | *.unitypackage 63 | *.app 64 | 65 | # Crashlytics generated file 66 | crashlytics-build.properties 67 | 68 | # Packed Addressables 69 | /[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin* 70 | 71 | # Temporary auto-generated Android Assets 72 | /[Aa]ssets/[Ss]treamingAssets/aa.meta 73 | /[Aa]ssets/[Ss]treamingAssets/aa/* 74 | -------------------------------------------------------------------------------- /Samples/SyncEventTest.cs: -------------------------------------------------------------------------------- 1 | using CoEvents; 2 | using UnityEngine; 3 | 4 | 5 | //不带返回值 6 | public interface IMyEvent : ISendEvent { } 7 | 8 | //带返回值 9 | public interface ICustomCallEvent : ICallEvent { } 10 | 11 | 12 | public class SyncEventTest : MonoBehaviour 13 | { 14 | // Start is called before the first frame update 15 | void Start() 16 | { 17 | //*********************注册/***************************************** 18 | //1.委托注册 19 | this.Operator().Subscribe((x, y) => 20 | { 21 | Debug.Log(x); 22 | //Do something here. 23 | }); 24 | 25 | //2.方法注册 26 | this.Operator().Subscribe(Aaaa); 27 | 28 | //带返回值 29 | this.Operator().Subscribe(Bbbb); 30 | //******************************************************************* 31 | //可以在其他脚本和类,任意地方调用下面的方法 32 | this.Operator().Send(10, "10"); 33 | string str = this.Operator().CallFirst(10); 34 | 35 | //*********************************小建议 36 | //如果在静态类中无法使用this 37 | //CoEvent.Instance.Operator<> 38 | 39 | //快速开启协程 40 | //CoEvent.Mono.StartCoroutine() 41 | 42 | 43 | //***************************************** 44 | 45 | 46 | } 47 | 48 | 49 | 50 | private void OnDestroy() 51 | { 52 | this.Operator().UnSubscribeAll(); 53 | this.Operator().UnSubscribe(Bbbb); 54 | } 55 | 56 | 57 | void Aaaa(int x, string y) 58 | { 59 | Debug.Log(x); 60 | } 61 | 62 | string Bbbb(int y) 63 | { 64 | return y.ToString(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/CoOperator.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Internal; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Runtime.CompilerServices; 6 | 7 | namespace CoEvents 8 | { 9 | public class CoOperator : ICoVarOperator 10 | { 11 | public List Events { get; private set; } = new List(); 12 | 13 | /// 14 | /// 委托数 15 | /// 16 | public int Count => Events.Count; 17 | 18 | public int IntervalIndex { get; private set; } = 0; 19 | 20 | 21 | /// 22 | /// 清空操作器 23 | /// 24 | public void Clear() 25 | { 26 | Events.Clear(); 27 | } 28 | 29 | 30 | 31 | public void Add(Delegate dele) 32 | { 33 | Events.Add(dele); 34 | } 35 | 36 | public bool Remove(Delegate dele) 37 | { 38 | int index = Events.IndexOf(dele); 39 | if (index <= IntervalIndex) --IntervalIndex; 40 | 41 | return Events.Remove(dele); 42 | } 43 | 44 | public bool GetNext(out Delegate dele) 45 | { 46 | if (IntervalIndex >= 0 && IntervalIndex < Events.Count) 47 | { 48 | 49 | dele = Events[IntervalIndex++]; 50 | return true; 51 | } 52 | dele = null; 53 | return false; 54 | } 55 | 56 | public void Reset() 57 | { 58 | IntervalIndex = 0; 59 | } 60 | 61 | } 62 | 63 | 64 | 65 | internal static class CoV_EX 66 | { 67 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 68 | internal static CoOperator GetOperator(this ICoVarOperator ico) 69 | { 70 | return (CoOperator)ico; 71 | } 72 | 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/AsyncTreeTokenNode.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 此类为异步令牌的底层实现,要求形成任务树结构 6 | */ 7 | 8 | using System.Diagnostics; 9 | using System.Runtime.CompilerServices; 10 | 11 | namespace CoEvents.Async.Internal 12 | { 13 | public class AsyncTreeTokenNode : IAuthorization 14 | { 15 | 16 | /// 17 | /// 授权状态,代表当前任务是否被挂起,也决定了状态机是否能够继续前进 18 | /// 19 | public bool Authorization { get; internal set; } = true; 20 | //当前MethodBuilder执行的任务 21 | public IAsyncTokenProperty Current; 22 | 23 | 24 | //MethodBuilder代表的任务 25 | public IAsyncTokenProperty Root; 26 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 27 | public AsyncTreeTokenNode(IAsyncTokenProperty Root, IAsyncTokenProperty Current) 28 | { 29 | this.Current = Current; 30 | this.Root = Root; 31 | } 32 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 33 | public void Yield() 34 | { 35 | Authorization = false; 36 | //非Builder任务则空 37 | if (Current != Root) this.Current.Token?.Yield(); 38 | } 39 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 40 | public void Continue() 41 | { 42 | Authorization = true; 43 | if (Current != Root) this.Current.Token?.Continue(); 44 | } 45 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 46 | public void Cancel() 47 | { 48 | Authorization = false; 49 | if (Current != Root) 50 | { 51 | this.Current.Token?.Cancel(); 52 | } 53 | 54 | Current.SetCancel(); 55 | } 56 | 57 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 58 | public bool IsRunning() => Authorization; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Ex/CoTask_Ex.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Runtime.CompilerServices; 4 | 5 | namespace CoEvents.Async 6 | { 7 | public static partial class CoTask_Ex 8 | { 9 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:删除未使用的参数", Justification = "<挂起>")] 10 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 11 | public static void Discard(this ICoTask task) 12 | { 13 | // empty 14 | } 15 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 16 | public static async CoTask Invoke(this CoTask task) 17 | { 18 | await task; 19 | } 20 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 21 | public static async CoTask Invoke(this CoTask task) 22 | { 23 | return await task; 24 | } 25 | 26 | 27 | /// 28 | /// 为指定异步任务设置令牌,可以取消和挂起 29 | /// 30 | /// 31 | /// 32 | /// 33 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 34 | public static CoTask WithToken(this CoTask task, out AsyncToken token) 35 | { 36 | var tok = AsyncToken.Create(); 37 | tok.node = task.Token; 38 | token = tok; 39 | return task; 40 | } 41 | 42 | /// 43 | /// 为指定异步任务设置令牌,可以取消和挂起 44 | /// 45 | /// 46 | /// 47 | /// 48 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 49 | public static CoTask WithToken(this CoTask task, out AsyncToken token, Action cancelCallback = null) 50 | { 51 | var tok = AsyncToken.Create(); 52 | tok.node = task.Token; 53 | token = tok; 54 | if (cancelCallback != null) tok.OnCanceled += cancelCallback; 55 | return task; 56 | } 57 | 58 | 59 | 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CoEvent 2 | 3 | CoEvent是一个基于**观察者模式**的**事件系统**,它支持**参数类型的约束**,**显式化事件定义**以便于多人协作,能防止参数类型误判,优化协作时的通信规范。 4 | 支持Unity3D 2021.1以上和.NETCORE平台的开发。 5 | 6 | 7 | ## 一、功能与模块 8 | 9 | ### 1.协变事件系统CoEvent 10 | 11 | ```c# 12 | 1.参数类型约束,不会错判,便于协作查找定义 13 | 2.支持带返回值不带返回值两种调用类型 14 | ``` 15 | 16 | 17 | 18 | ## 二、使用 19 | 20 | 21 | 1).前期配置: 22 | 23 | ```c# 24 | 在Unity2021及以上使用跳过这一步 25 | 如果在NET CORE使用请定位错误信息并根据提示修改宏定义。 26 | ``` 27 | 28 | 2).事件定义 29 | 30 | 定义事件有两种接口,ISendEvent是不带返回值的,ICallEvent是带返回值的 31 | 32 | ```csharp 33 | //这一部分如果涉及多人开发,您可以把所有事件放在一个文件夹下,也可也放在事件的最相关处,这样做可以方便查阅 34 | 35 | public interface MyEvent: ISendEvent<参数类型...> 36 | public interface MyEvent: ICallEvent<参数类型...返回值类型> 37 | ``` 38 | 39 | 3).注册和取消事件 40 | 41 | 仅在注册后才能执行发送和调用 42 | 43 | ``` csharp 44 | this.Operator<消息类型接口>().Subcribe(MyAction); 45 | 46 | //请注意,C#的委托闭包问题,也就是说如果您不取消事件,委托内被提取的引用对象将不会被GC自动回收,这是C#委托常见的一个内存泄漏陷阱。这是一个几乎全部事件系统都存在的问题。 47 | this.Operator<消息类型接口>().UnSubcribe(MyAction); 48 | ``` 49 | 50 | 4).调用和发送 51 | 52 | ``` csharp 53 | //调用全部 54 | this.Operator<消息类型接口>().Send(...参数们); 55 | //调用全部 56 | var results = this.Operator<消息类型接口>().Call(...参数们); 57 | //调用第一个 58 | var result = this.Operator<消息类型接口>().CallFirst(参数们); 59 | ``` 60 | 61 | 5).例程 62 | 63 | ```csharp 64 | using CoEvent; 65 | using UnityEngine; 66 | 67 | public interface IMyTest : ISendEvent { } 68 | public class Test : MonoBehaviour 69 | { 70 | 71 | void Ttt(int t,int k) 72 | { 73 | Debug.Log($"{t}:{k}"); 74 | } 75 | 76 | void Start() 77 | { 78 | this.Operator().Subscribe(Ttt); 79 | this.Operator().Send(10,100); 80 | } 81 | 82 | void OnDestroy() 83 | { 84 | this.Operator().UnSubscribe(Ttt); 85 | } 86 | } 87 | ``` 88 | 89 | 90 | ## 三、默认内置对象池的使用 91 | 92 | CoEvent为了优化性能,不得不引入对象池来进行对象复用,但是许多独立工具集和架构,插件,都含有自己的对象池,这样在引入大量插件后容易导致对象池代码重复。 93 | 94 | CoEvent引入了一个性能较高,且功能较为简单的轻量对象池,且允许用户进行替换,CoEvent类中定义里一个Pool属性,**默认指定为CoDeaultPool**,您可以**将他设置为null,这时CoEvent将不会使用Poo**l。 95 | 96 | 同样的,您可以使用Pool进行一些其他对象的存储和复用,例如 97 | 98 | ```csharp 99 | T item = CoEvent.Pool?.Allocate(); 100 | CoEvent.Pool?Recycle(item); 101 | ``` 102 | 103 | 同样的,也有针对于GameObject的API,都采用比较轻量化的实现。 104 | 105 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/ICoEventBase.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Internal; 2 | 3 | //建议不要随便使用这个命名空间下的东西 4 | namespace CoEvents.Internal 5 | { 6 | 7 | //基础接口是没法处理事件的,没有任何匹配的功能,简称没用 8 | public interface ICoEventBase { } 9 | 10 | 11 | 12 | //泛型接口不够安全,能Send也能Call 13 | public interface IGenericEvent : ICoEventBase { } 14 | public interface IGenericEvent : ICoEventBase { } 15 | public interface IGenericEvent : ICoEventBase { } 16 | public interface IGenericEvent : ICoEventBase { } 17 | public interface IGenericEvent : ICoEventBase { } 18 | public interface IGenericEvent : ICoEventBase { } 19 | public interface IGenericEvent : ICoEventBase { } 20 | 21 | 22 | //这两个是Base,也没能处理的事件,简称没用 23 | public interface ISendEventBase : ICoEventBase { } 24 | 25 | public interface ICallEventBase : ICoEventBase { } 26 | } 27 | 28 | 29 | namespace CoEvents 30 | { 31 | #pragma warning disable 32 | 33 | 34 | 35 | 36 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 37 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 38 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 39 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 40 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 41 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 42 | public interface ISendEvent : ISendEventBase, IGenericEvent { } 43 | 44 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 45 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 46 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 47 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 48 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 49 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 50 | public interface ICallEvent : ICallEventBase, IGenericEvent { } 51 | 52 | 53 | 54 | 55 | #pragma warning restore 56 | } 57 | -------------------------------------------------------------------------------- /CoEvent/Runtime/CoEvent.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Internal; 2 | using System; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | namespace CoEvents 7 | { 8 | public static class CoEvent 9 | { 10 | //事件容器 11 | internal static Dictionary> container = new Dictionary>(); 12 | //移除标记 13 | internal static HashSet removeMarks = new HashSet(); 14 | 15 | //如果认为容器中空余的事件Operator占内存,则随便写个脚本计时调用这个方法即可。 16 | public static void ReleaseEmpty() 17 | { 18 | foreach (var con in container) 19 | { 20 | if (con.Value.Count == 0) removeMarks.Add(con.Key); 21 | } 22 | foreach (var tp in removeMarks) 23 | { 24 | container.Remove(tp); 25 | } 26 | removeMarks.Clear(); 27 | } 28 | 29 | //初始化标记 30 | internal static bool Initialized { get; private set; } = false; 31 | 32 | private static CoEventPublisher monoPublisher = null; 33 | 34 | //自动创建Publisher发布简单生命周期 35 | [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] 36 | public static void InitPublisher() 37 | { 38 | if (Initialized) return; 39 | GameObject publisher = new GameObject("CoEventPublisher"); 40 | GameObject.DontDestroyOnLoad(publisher); 41 | monoPublisher = publisher.AddComponent(); 42 | Initialized = true; 43 | } 44 | 45 | /// 46 | /// 在静态类中无法使用this,则使用CoEvents.Instance.Operator 47 | /// 48 | public readonly static object Instance = new object(); 49 | 50 | /// 51 | /// 默认对象池,如果为null则不开启,默认最大容量为1000个 52 | /// 53 | public static IPool Pool { get; set; } = new CoDefaultPool(1000); 54 | 55 | /// 56 | /// 异常处理器,所有异常都使用此方法处理 57 | /// 58 | 59 | public static Action ExceptionHandler = (x) => throw x; 60 | 61 | public static MonoBehaviour Mono => monoPublisher; 62 | public static ICoVarOperator Update { get; } = Instance.Operator(); 63 | public static ICoVarOperator LateUpdate { get; } = Instance.Operator(); 64 | public static ICoVarOperator FixedUpdate { get; } = Instance.Operator(); 65 | } 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/AsyncToken.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 提供异步令牌给用户进行操作,方便用户挂起,结束异步任务 6 | */ 7 | 8 | 9 | using CoEvents.Async.Internal; 10 | using System; 11 | using System.Diagnostics; 12 | using System.Runtime.CompilerServices; 13 | 14 | namespace CoEvents.Async 15 | { 16 | 17 | /// 18 | /// 每个小任务都只能有这三种状态 19 | /// 20 | 21 | public enum AsyncStatus 22 | { 23 | //等待ing 24 | Pending, 25 | //挂起 26 | Yield, 27 | //结束 28 | Completed 29 | } 30 | public sealed class AsyncToken 31 | { 32 | 33 | public event Action OnCanceled = null; 34 | 35 | public static AsyncToken Create() 36 | { 37 | AsyncToken token; 38 | if (CoEvent.Pool != null) token = (AsyncToken)CoEvent.Pool.Allocate(typeof(AsyncToken)); 39 | else token = new AsyncToken(); 40 | token.Status = AsyncStatus.Pending; 41 | token.node = default; 42 | return token; 43 | } 44 | public static void Recycle(AsyncToken token) 45 | { 46 | token.Status = AsyncStatus.Pending; 47 | token.node = default; 48 | if (CoEvent.Pool != null) CoEvent.Pool.Recycle(typeof(AsyncToken), token); 49 | 50 | } 51 | 52 | 53 | internal AsyncTreeTokenNode node; 54 | 55 | public AsyncStatus Status { get; private set; } = AsyncStatus.Pending; 56 | 57 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 58 | public void Yield() 59 | { 60 | if (Status == AsyncStatus.Completed) throw new InvalidOperationException("尝试挂起已经结束的任务是无效的"); 61 | Status = AsyncStatus.Yield; 62 | node.Yield(); 63 | } 64 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 65 | public void Continue() 66 | { 67 | if (Status == AsyncStatus.Completed) throw new InvalidOperationException("尝试取消已经结束的任务是无效的"); 68 | Status = AsyncStatus.Pending; 69 | node.Continue(); 70 | } 71 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 72 | public void Cancel() 73 | { 74 | if (Status == AsyncStatus.Completed) throw new InvalidOperationException(); 75 | Status = AsyncStatus.Completed; 76 | node.Cancel(); 77 | OnCanceled?.Invoke(); 78 | } 79 | 80 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 81 | public void Recycle() => AsyncToken.Recycle(this); 82 | 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/Extensions_Send.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | namespace CoEvents 4 | { 5 | public static partial class MessageExtensions 6 | { /// 7 | /// 发布 8 | /// 9 | /// 10 | public static void Send(this ICoVarOperator container) 11 | { 12 | var mop = container.GetOperator(); 13 | while (mop.GetNext(out var current)) 14 | { 15 | ((Action)current).Invoke(); 16 | } 17 | mop.Reset(); 18 | } 19 | /// 20 | /// 发布 21 | /// 22 | /// 23 | public static void Send(this ICoVarOperator> container, T1 arg1) 24 | { 25 | var mop = container.GetOperator(); 26 | while (mop.GetNext(out var current)) 27 | { 28 | ((Action)current).Invoke(arg1); 29 | } 30 | mop.Reset(); 31 | } 32 | public static void Send(this ICoVarOperator> container, T1 arg1, T2 arg2) 33 | { 34 | var mop = container.GetOperator(); 35 | while (mop.GetNext(out var current)) 36 | { 37 | ((Action)current).Invoke(arg1, arg2); 38 | } 39 | mop.Reset(); 40 | } 41 | /// 42 | /// 发布 43 | /// 44 | /// 45 | public static void Send(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3) 46 | { 47 | var mop = container.GetOperator(); 48 | while (mop.GetNext(out var current)) 49 | { 50 | ((Action)current).Invoke(arg1, arg2, arg3); 51 | } 52 | mop.Reset(); 53 | } 54 | public static void Send(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3, T4 arg4) 55 | { 56 | var mop = container.GetOperator(); 57 | while (mop.GetNext(out var current)) 58 | { 59 | ((Action)current).Invoke(arg1, arg2, arg3, arg4); 60 | } 61 | mop.Reset(); 62 | } 63 | /// 64 | /// 发布 65 | /// 66 | /// 67 | public static void Send(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) 68 | { 69 | var mop = container.GetOperator(); 70 | while (mop.GetNext(out var current)) 71 | { 72 | ((Action)current).Invoke(arg1, arg2, arg3, arg4, arg5); 73 | } 74 | mop.Reset(); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Pool/CoDefaultPool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | namespace CoEvents 7 | { 8 | public class CoDefaultPool : IPool 9 | { 10 | private Dictionary pool = new Dictionary(); 11 | 12 | public int MaxCount { get; set; } = 1000; 13 | 14 | public CoDefaultPool() { } 15 | public CoDefaultPool(int maxCount) => MaxCount = maxCount; 16 | 17 | public object Allocate(Type type) 18 | { 19 | if (!pool.ContainsKey(type)) 20 | { 21 | pool.Add(type, new Queue()); 22 | } 23 | var queue = pool[type]; 24 | if (queue.Count == 0) 25 | { 26 | queue.Enqueue(Activator.CreateInstance(type)); 27 | } 28 | return queue.Dequeue(); 29 | } 30 | 31 | public void Recycle(Type type, object item) 32 | { 33 | if (!pool.ContainsKey(type)) 34 | { 35 | pool.Add(type, new Queue()); 36 | } 37 | var queue = pool[type]; 38 | if (queue.Count >= MaxCount) 39 | { 40 | queue.Enqueue(item); 41 | } 42 | } 43 | 44 | 45 | public T Allocate() 46 | { 47 | return (T)Allocate(typeof(T)); 48 | } 49 | public void Recycle(object item) 50 | { 51 | Recycle(typeof(T), item); 52 | } 53 | 54 | 55 | public int GameObjectMaxCount { get; set; } = 1000; 56 | 57 | 58 | private Dictionary> gos = new Dictionary>(); 59 | 60 | private Dictionary> createFuncs = new Dictionary>(); 61 | private Dictionary> destroyActions = new Dictionary>(); 62 | 63 | public void SetGameObjectBehaviour(int key, Func onCreate, Action onDestroy = null) 64 | { 65 | if (createFuncs.ContainsKey(key)) 66 | { 67 | createFuncs[key] = onCreate; 68 | destroyActions[key] = onDestroy; 69 | } 70 | else 71 | { 72 | createFuncs.Add(key, onCreate); 73 | destroyActions.Add(key, onDestroy); 74 | } 75 | } 76 | 77 | public GameObject AllocateGameObject(int key) 78 | { 79 | if (!createFuncs.ContainsKey(key)) throw new InvalidOperationException("Please set CreateFunc before call Allocate"); 80 | if (!gos.ContainsKey(key)) 81 | { 82 | gos.Add(key, new Queue()); 83 | } 84 | if (gos[key].Count < 0) gos[key].Enqueue(createFuncs[key]()); 85 | 86 | return gos[key].Dequeue(); 87 | } 88 | 89 | public void RecycleGameObject(int key, GameObject go) 90 | { 91 | if (!createFuncs.ContainsKey(key)) throw new InvalidOperationException("Please set DestroyAction before call Recycle"); 92 | if (!gos.ContainsKey(key)) 93 | { 94 | gos.Add(key, new Queue()); 95 | } 96 | if (gos[key].Count >= GameObjectMaxCount) destroyActions[key]?.Invoke(go); 97 | else gos[key].Enqueue(go); 98 | } 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/Extensions_Condition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CoEvents 4 | { 5 | public static class Extensions_Condition 6 | { 7 | public class ConditionMotor 8 | { 9 | public static ConditionMotor Create() 10 | { 11 | if (CoEvent.Pool == null) return new ConditionMotor(); 12 | return (ConditionMotor)CoEvent.Pool.Allocate(typeof(ConditionMotor)); 13 | } 14 | public static void Recycle(ConditionMotor motor) 15 | { 16 | motor.action = null; 17 | motor.removeWhen = null; 18 | motor.invokeWhen = null; 19 | if (CoEvent.Pool == null) return; 20 | CoEvent.Pool.Recycle(typeof(ConditionMotor), motor); 21 | } 22 | 23 | private void Update(float x) 24 | { 25 | if (invokeWhen == null ? true : invokeWhen()) 26 | { 27 | action?.Invoke(); 28 | } 29 | if (removeWhen == null ? false : removeWhen()) 30 | { 31 | CoEvent.Instance.Operator().UnSubscribe(Update); 32 | Recycle(this); 33 | } 34 | } 35 | internal ConditionMotor SetUpdateInvoke(Action action) 36 | { 37 | this.action = action; 38 | CoEvent.Instance.Operator().Subscribe(Update); 39 | return this; 40 | } 41 | private void LateUpdate() 42 | { 43 | if (invokeWhen == null ? true : invokeWhen()) 44 | { 45 | action?.Invoke(); 46 | } 47 | if (removeWhen == null ? false : removeWhen()) 48 | { 49 | CoEvent.Instance.Operator().UnSubscribe(LateUpdate); 50 | Recycle(this); 51 | } 52 | } 53 | 54 | internal ConditionMotor SetLateUpdateInvoke(Action action) 55 | { 56 | this.action = action; 57 | CoEvent.Instance.Operator().Subscribe(LateUpdate); 58 | return this; 59 | } 60 | 61 | private void FixedUpdate() 62 | { 63 | if (invokeWhen == null ? true : invokeWhen()) 64 | { 65 | action?.Invoke(); 66 | } 67 | if (removeWhen == null ? false : removeWhen()) 68 | { 69 | CoEvent.Instance.Operator().UnSubscribe(FixedUpdate); 70 | Recycle(this); 71 | } 72 | } 73 | 74 | internal ConditionMotor SetFixedUpdateInvoke(Action action) 75 | { 76 | this.action = action; 77 | CoEvent.Instance.Operator().Subscribe(FixedUpdate); 78 | return this; 79 | } 80 | 81 | 82 | 83 | 84 | private Action action = null; 85 | private Func removeWhen = null; 86 | private Func invokeWhen = null; 87 | 88 | 89 | 90 | 91 | 92 | public ConditionMotor RemoveWhen(Func rm) 93 | { 94 | removeWhen = rm; 95 | return this; 96 | } 97 | public ConditionMotor Condition(Func im) 98 | { 99 | invokeWhen = im; 100 | return this; 101 | } 102 | } 103 | public static ConditionMotor Invoke(this ICoVarOperator oper, Action action) 104 | { 105 | var motor = ConditionMotor.Create(); 106 | return motor.SetUpdateInvoke(action); 107 | } 108 | public static ConditionMotor Invoke(this ICoVarOperator oper, Action action) 109 | { 110 | var motor = ConditionMotor.Create(); 111 | return motor.SetUpdateInvoke(action); 112 | } 113 | public static ConditionMotor Invoke(this ICoVarOperator oper, Action action) 114 | { 115 | var motor = ConditionMotor.Create(); 116 | return motor.SetUpdateInvoke(action); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/CounterCall.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace CoEvents.Async 7 | { 8 | public sealed class CounterCall 9 | { 10 | 11 | 12 | public static CounterCall Create() 13 | { 14 | CounterCall call = null; 15 | if (CoEvent.Pool != null) call = (CounterCall)CoEvent.Pool.Allocate(typeof(CounterCall)); 16 | else call = new CounterCall(); 17 | 18 | return call; 19 | } 20 | public static void Recycle(CounterCall call) 21 | { 22 | call.OnClick = null; 23 | call._counter = 0; 24 | call.ClickValue = 0; 25 | call.OnceRecycle = false; 26 | if (CoEvent.Pool != null) return; 27 | CoEvent.Pool.Recycle(typeof(CounterCall), call); 28 | } 29 | 30 | 31 | 32 | /// 33 | /// 是否达到一次ClickValue就自动回收到对象池或者销毁 34 | /// 35 | public bool OnceRecycle { get; set; } = false; 36 | private int _counter; 37 | /// 38 | /// 当前计数数量 39 | /// 40 | public int Count 41 | { 42 | get => _counter; 43 | set 44 | { 45 | _counter = value; 46 | if (value == ClickValue) 47 | { 48 | OnClick?.Invoke(); 49 | if (OnceRecycle) Recycle(this); 50 | } 51 | } 52 | } 53 | 54 | 55 | /// 56 | /// 预期触发值 57 | /// 58 | public int ClickValue { get; set; } = 0; 59 | 60 | /// 61 | /// 触发事件 62 | /// 63 | public event Action OnClick = null; 64 | 65 | private Action plusOne = null; 66 | /// 67 | /// 默认实现的加一行为,第一次访问产生GC,代替自定义lambda减少GC产出 68 | /// 69 | public Action PlusOne 70 | { 71 | get 72 | { 73 | if (plusOne == null) 74 | { 75 | plusOne = () => { ++Count; }; 76 | } 77 | return plusOne; 78 | } 79 | } 80 | 81 | 82 | } 83 | 84 | 85 | public class CounterCall 86 | { 87 | 88 | public static CounterCall Create() 89 | { 90 | CounterCall call = null; 91 | if (CoEvent.Pool != null) call = (CounterCall)CoEvent.Pool.Allocate(typeof(CounterCall)); 92 | else call = new CounterCall(); 93 | 94 | return call; 95 | } 96 | public static void Recycle(CounterCall call) 97 | { 98 | call.OnClick = null; 99 | call._counter = 0; 100 | call.ClickValue = 0; 101 | call.OnceRecycle = false; 102 | call.Results.Clear(); 103 | if (CoEvent.Pool != null) return; 104 | CoEvent.Pool.Recycle(typeof(CounterCall), call); 105 | } 106 | 107 | 108 | 109 | 110 | /// 111 | /// 是否达到一次ClickValue就自动回收到对象池或者销毁 112 | /// 113 | public bool OnceRecycle { get; set; } = false; 114 | private int _counter; 115 | /// 116 | /// 当前计数数量 117 | /// 118 | public int Count 119 | { 120 | get => _counter; 121 | set 122 | { 123 | _counter = value; 124 | if (value == ClickValue) 125 | { 126 | OnClick?.Invoke(Results); 127 | if (OnceRecycle) Recycle(this); 128 | } 129 | } 130 | } 131 | 132 | 133 | /// 134 | /// 预期触发值 135 | /// 136 | public int ClickValue { get; set; } = 0; 137 | 138 | /// 139 | /// 触发事件 140 | /// 141 | public event Action> OnClick = null; 142 | 143 | 144 | public List Results { get; set; } = new List(); 145 | 146 | private Action plusOne = null; 147 | /// 148 | /// 默认实现的加一行为,第一次访问产生GC,代替自定义lambda减少GC产出 149 | /// 150 | public Action PlusOne 151 | { 152 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 153 | get 154 | { 155 | if (plusOne == null) 156 | { 157 | plusOne = (x) => { ++Count; Results.Add(x); }; 158 | } 159 | return plusOne; 160 | } 161 | } 162 | 163 | 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/CoTaskBuilder.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Async.Internal; 2 | using System; 3 | using System.Diagnostics; 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace CoEvents.Async 7 | { 8 | public struct CoTaskBuilder 9 | { 10 | 11 | // 1. Static Create method 12 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 13 | public static CoTaskBuilder Create() => new CoTaskBuilder(CoTask.Create()); 14 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 15 | public CoTaskBuilder(CoTask task) => this.task = task; 16 | 17 | private readonly CoTask task; 18 | // 2. TaskLike Current 19 | //[DebuggerHidden] 20 | public CoTask Task => task; 21 | 22 | 23 | 24 | // 3. Start 构造之后开启状态机 25 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 26 | public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine 27 | { 28 | stateMachine.MoveNext(); 29 | } 30 | 31 | // 4. SetException 32 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 33 | public void SetException(Exception exception) 34 | { 35 | UnityEngine.Debug.Log(exception.ToString()); 36 | task.SetException(exception); 37 | } 38 | 39 | // 5. SetResult 40 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 41 | public void SetResult() 42 | { 43 | task.SetResult(); 44 | } 45 | 46 | // 6. AwaitOnCompleted 47 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 48 | public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) 49 | where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine 50 | { 51 | task.Token.Current = awaiter as IAsyncTokenProperty; 52 | awaiter.OnCompleted(stateMachine.MoveNext); 53 | //UnityEngine.Debug.Log("100"); 54 | } 55 | 56 | // 7. AwaitUnsafeOnCompleted 57 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 58 | public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) 59 | where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine 60 | { 61 | 62 | task.Token.Current = awaiter as IAsyncTokenProperty; 63 | awaiter.OnCompleted(stateMachine.MoveNext); 64 | //UnityEngine.Debug.Log("100"); 65 | } 66 | 67 | // 9. SetStateMachine 68 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 69 | public void SetStateMachine(IAsyncStateMachine stateMachine) 70 | { 71 | 72 | } 73 | } 74 | 75 | public struct CoTaskBuilder 76 | { 77 | 78 | // 1. Static Create method 79 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 80 | public static CoTaskBuilder Create() => new CoTaskBuilder(CoTask.Create()); 81 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 82 | public CoTaskBuilder(CoTask task) => this.task = task; 83 | 84 | private readonly CoTask task; 85 | // 2. TaskLike Current 86 | //[DebuggerHidden] 87 | public CoTask Task => task; 88 | 89 | 90 | 91 | // 3. Start 构造之后开启状态机 92 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 93 | public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine 94 | { 95 | stateMachine.MoveNext(); 96 | } 97 | 98 | // 4. SetException 99 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 100 | public void SetException(Exception exception) 101 | { 102 | task.SetException(exception); 103 | } 104 | 105 | // 5. SetResult 106 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 107 | public void SetResult(T result) 108 | { 109 | task.SetResult(result); 110 | } 111 | 112 | // 6. AwaitOnCompleted 113 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 114 | public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) 115 | where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine 116 | { 117 | task.Token.Current = awaiter as IAsyncTokenProperty; 118 | awaiter.OnCompleted(stateMachine.MoveNext); 119 | } 120 | 121 | // 7. AwaitUnsafeOnCompleted 122 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 123 | public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) 124 | where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine 125 | { 126 | 127 | task.Token.Current = awaiter as IAsyncTokenProperty; 128 | awaiter.OnCompleted(stateMachine.MoveNext); 129 | } 130 | 131 | // 9. SetStateMachine 132 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 133 | public void SetStateMachine(IAsyncStateMachine stateMachine) 134 | { 135 | 136 | } 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/Extensions_Subscribe.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Runtime.CompilerServices; 4 | 5 | namespace CoEvents 6 | { 7 | public static partial class MessageExtensions 8 | { 9 | /// 10 | /// 订阅 11 | /// 12 | /// 13 | /// 14 | 15 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 16 | public static void Subscribe(this ICoVarOperator container, Action message) 17 | => container.GetOperator().Events.Add(message); 18 | 19 | 20 | /// 21 | /// 订阅 22 | /// 23 | /// 24 | /// 25 | 26 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 27 | public static void Subscribe(this ICoVarOperator> container, Action message) 28 | => container.GetOperator().Events.Add(message); 29 | 30 | 31 | /// 32 | /// 订阅 33 | /// 34 | /// 35 | /// 36 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 37 | public static void Subscribe(this ICoVarOperator> container, Action message) 38 | => container.GetOperator().Events.Add(message); 39 | /// 40 | /// 订阅 41 | /// 42 | /// 43 | /// 44 | 45 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 46 | public static void Subscribe(this ICoVarOperator> container, Action message) 47 | => container.GetOperator().Events.Add(message); 48 | /// 49 | /// 订阅 50 | /// 51 | /// 52 | /// 53 | 54 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 55 | public static void Subscribe(this ICoVarOperator> container, Action message) 56 | => container.GetOperator().Events.Add(message); 57 | /// 58 | /// 订阅 59 | /// 60 | /// 61 | /// 62 | 63 | 64 | 65 | /// 66 | /// 订阅 67 | /// 68 | /// 69 | /// 70 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 71 | public static void Subscribe(this ICoVarOperator> container, Action message) 72 | => container.GetOperator().Events.Add(message); 73 | 74 | //--------------------------------------------------------------------------------------------------------------------------------------- 75 | 76 | /// 77 | /// 订阅 78 | /// 79 | /// 80 | /// 81 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 82 | public static void Subscribe(this ICoVarOperator> container, Func message) 83 | => container.GetOperator().Events.Add(message); 84 | 85 | 86 | /// 87 | /// 订阅 88 | /// 89 | /// 90 | /// 91 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 92 | public static void Subscribe(this ICoVarOperator> container, Func message) 93 | => container.GetOperator().Events.Add(message); 94 | 95 | /// 96 | /// 订阅 97 | /// 98 | /// 99 | /// 100 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 101 | public static void Subscribe(this ICoVarOperator> container, Func message) 102 | => container.GetOperator().Events.Add(message); 103 | 104 | /// 105 | /// 订阅 106 | /// 107 | /// 108 | /// 109 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 110 | public static void Subscribe(this ICoVarOperator> container, Func message) 111 | => container.GetOperator().Events.Add(message); 112 | 113 | 114 | /// 115 | /// 订阅 116 | /// 117 | /// 118 | /// 119 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 120 | public static void Subscribe(this ICoVarOperator> container, Func message) 121 | => container.GetOperator().Events.Add(message); 122 | 123 | 124 | /// 125 | /// 订阅 126 | /// 127 | /// 128 | /// 129 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 130 | public static void Subscribe(this ICoVarOperator> container, Func message) 131 | => container.GetOperator().Events.Add(message); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/Extensions_Call.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CoEvents 5 | { 6 | 7 | public static partial class MessageExtensions 8 | { 9 | public static List Call(this ICoVarOperator> container) 10 | { 11 | var mop = container.GetOperator(); 12 | List result = new List(); 13 | 14 | while (mop.GetNext(out var dele)) 15 | { 16 | result.Add(((Func)dele).Invoke()); 17 | } 18 | mop.Reset(); 19 | return result; 20 | } 21 | 22 | 23 | public static List Call(this ICoVarOperator> container, T1 arg1) 24 | { 25 | var mop = container.GetOperator(); 26 | List result = new List(); 27 | 28 | while (mop.GetNext(out var dele)) 29 | { 30 | result.Add(((Func)dele).Invoke(arg1)); 31 | } 32 | mop.Reset(); 33 | return result; 34 | } 35 | 36 | public static List Call(this ICoVarOperator> container, T1 arg1, T2 arg2) 37 | { 38 | var mop = container.GetOperator(); 39 | List result = new List(); 40 | 41 | while (mop.GetNext(out var dele)) 42 | { 43 | result.Add(((Func)dele).Invoke(arg1, arg2)); 44 | } 45 | mop.Reset(); 46 | return result; 47 | } 48 | 49 | 50 | 51 | public static List Call(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3) 52 | { 53 | var mop = container.GetOperator(); 54 | List result = new List(); 55 | 56 | while (mop.GetNext(out var dele)) 57 | { 58 | result.Add(((Func)dele).Invoke(arg1, arg2, arg3)); 59 | } 60 | mop.Reset(); 61 | return result; 62 | } 63 | 64 | 65 | public static List Call(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3, T4 arg4) 66 | { 67 | var mop = container.GetOperator(); 68 | List result = new List(); 69 | 70 | while (mop.GetNext(out var dele)) 71 | { 72 | result.Add(((Func)dele).Invoke(arg1, arg2, arg3, arg4)); 73 | } 74 | mop.Reset(); 75 | return result; 76 | } 77 | 78 | 79 | public static List Call(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) 80 | { 81 | var mop = container.GetOperator(); 82 | List result = new List(); 83 | 84 | while (mop.GetNext(out var dele)) 85 | { 86 | result.Add(((Func)dele).Invoke(arg1, arg2, arg3, arg4, arg5)); 87 | } 88 | mop.Reset(); 89 | return result; 90 | } 91 | 92 | 93 | 94 | 95 | 96 | public static T1 CallFirst(this ICoVarOperator> container) 97 | { 98 | var mop = container.GetOperator(); 99 | 100 | if (mop.GetNext(out var dele)) 101 | { 102 | mop.Reset(); 103 | return ((Func)dele).Invoke(); 104 | } 105 | 106 | return default; 107 | } 108 | 109 | 110 | public static T2 CallFirst(this ICoVarOperator> container, T1 arg1) 111 | { 112 | var mop = container.GetOperator(); 113 | 114 | if (mop.GetNext(out var dele)) 115 | { 116 | mop.Reset(); 117 | return ((Func)dele).Invoke(arg1); 118 | } 119 | 120 | return default; 121 | } 122 | 123 | public static T3 CallFirst(this ICoVarOperator> container, T1 arg1, T2 arg2) 124 | { 125 | var mop = container.GetOperator(); 126 | 127 | if (mop.GetNext(out var dele)) 128 | { 129 | mop.Reset(); 130 | return ((Func)dele).Invoke(arg1, arg2); 131 | } 132 | 133 | return default; 134 | } 135 | 136 | 137 | 138 | public static T4 CallFirst(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3) 139 | { 140 | var mop = container.GetOperator(); 141 | 142 | if (mop.GetNext(out var dele)) 143 | { 144 | mop.Reset(); 145 | return ((Func)dele).Invoke(arg1, arg2, arg3); 146 | } 147 | 148 | return default; 149 | } 150 | 151 | 152 | public static T5 CallFirst(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3, T4 arg4) 153 | { 154 | var mop = container.GetOperator(); 155 | 156 | if (mop.GetNext(out var dele)) 157 | { 158 | mop.Reset(); 159 | return ((Func)dele).Invoke(arg1, arg2, arg3, arg4); 160 | } 161 | 162 | return default; 163 | } 164 | 165 | 166 | public static T6 CallFirst(this ICoVarOperator> container, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) 167 | { 168 | var mop = container.GetOperator(); 169 | 170 | if (mop.GetNext(out var dele)) 171 | { 172 | mop.Reset(); 173 | return ((Func)dele).Invoke(arg1, arg2, arg3, arg4, arg5); 174 | } 175 | return default; 176 | } 177 | 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Event/Extensions_UnSubscribe.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Runtime.CompilerServices; 4 | 5 | namespace CoEvents 6 | { 7 | public static partial class MessageExtensions 8 | { 9 | /// 10 | /// 退订 11 | /// 12 | /// 13 | /// 14 | 15 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 16 | public static void UnSubscribe(this ICoVarOperator container, Action message) 17 | => container.GetOperator().Events.Remove(message); 18 | /// 19 | /// 退订 20 | /// 21 | /// 22 | /// 23 | 24 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 25 | public static void UnSubscribe(this ICoVarOperator> container, Action message) 26 | => container.GetOperator().Events.Remove(message); 27 | /// 28 | /// 退订 29 | /// 30 | /// 31 | /// 32 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 33 | 34 | public static void UnSubscribe(this ICoVarOperator> container, Action message) 35 | => container.GetOperator().Events.Remove(message); 36 | /// 37 | /// 退订 38 | /// 39 | /// 40 | /// 41 | 42 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 43 | public static void UnSubscribe(this ICoVarOperator> container, Action message) 44 | => container.GetOperator().Events.Remove(message); 45 | /// 46 | /// 退订 47 | /// 48 | /// 49 | /// 50 | 51 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 52 | public static void UnSubscribe(this ICoVarOperator> container, Action message) 53 | => container.GetOperator().Events.Remove(message); 54 | /// 55 | /// 退订 56 | /// 57 | /// 58 | /// 59 | 60 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 61 | public static void UnSubscribe(this ICoVarOperator> container, Action message) 62 | => container.GetOperator().Events.Remove(message); 63 | //----------------------------------------------------------------------------------------------------------------------------------- 64 | 65 | /// 66 | /// 退订 67 | /// 68 | /// 69 | /// 70 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 71 | public static void UnSubscribe(this ICoVarOperator> container, Func message) 72 | => container.GetOperator().Events.Remove(message); 73 | 74 | 75 | /// 76 | /// 退订 77 | /// 78 | /// 79 | /// 80 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 81 | public static void UnSubscribe(this ICoVarOperator> container, Func message) 82 | => container.GetOperator().Events.Remove(message); 83 | 84 | 85 | /// 86 | /// 退订 87 | /// 88 | /// 89 | /// 90 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 91 | public static void UnSubscribe(this ICoVarOperator> container, Func message) 92 | => container.GetOperator().Events.Remove(message); 93 | 94 | 95 | /// 96 | /// 退订 97 | /// 98 | /// 99 | /// 100 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 101 | public static void UnSubscribe(this ICoVarOperator> container, Func message) 102 | => container.GetOperator().Events.Remove(message); 103 | 104 | 105 | /// 106 | /// 退订 107 | /// 108 | /// 109 | /// 110 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 111 | public static void UnSubscribe(this ICoVarOperator> container, Func message) 112 | => container.GetOperator().Events.Remove(message); 113 | 114 | /// 115 | /// 退订 116 | /// 117 | /// 118 | /// 119 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 120 | public static void UnSubscribe(this ICoVarOperator> container, Func message) 121 | => container.GetOperator().Events.Remove(message); 122 | 123 | //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 124 | /// 125 | /// 退订 126 | /// 127 | /// 128 | /// 129 | 130 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 131 | public static void UnSubscribeAll(this ICoVarOperator container) 132 | => container.GetOperator().Clear(); 133 | /// 134 | /// 退订 135 | /// 136 | /// 137 | /// 138 | 139 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 140 | public static void UnSubscribeAll(this ICoVarOperator> container) 141 | => container.GetOperator().Clear(); 142 | /// 143 | /// 退订 144 | /// 145 | /// 146 | /// 147 | 148 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 149 | public static void UnSubscribeAll(this ICoVarOperator> container) 150 | => container.GetOperator().Clear(); 151 | /// 152 | /// 退订 153 | /// 154 | /// 155 | /// 156 | 157 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 158 | public static void UnSubscribeAll(this ICoVarOperator> container) 159 | => container.GetOperator().Clear(); 160 | /// 161 | /// 退订 162 | /// 163 | /// 164 | /// 165 | 166 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 167 | public static void UnSubscribeAll(this ICoVarOperator> container) 168 | => container.GetOperator().Clear(); 169 | /// 170 | /// 退订 171 | /// 172 | /// 173 | /// 174 | 175 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 176 | public static void UnSubscribeAll(this ICoVarOperator> container) 177 | => container.GetOperator().Clear(); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/Ex/CoTask.Await.cs: -------------------------------------------------------------------------------- 1 | /******************************************************************************************** 2 | * Author : YueZhenpeng 3 | * Date : 2023.2.25 4 | * Description : 5 | * 创建Async静态类以实现一些静态异步方法,比如等待,延迟等,方便用户进行使用 6 | */ 7 | 8 | 9 | using System; 10 | using System.Collections.Generic; 11 | namespace CoEvents.Async 12 | { 13 | public partial class CoTask 14 | { 15 | /// 16 | /// 延迟指定秒数 17 | /// 18 | /// 19 | /// 20 | public static CoTaskTimer Delay(float seconds) 21 | { 22 | var timer = CoTaskTimer.Create(); 23 | timer.EndTime = seconds; 24 | return timer; 25 | } 26 | /// 27 | /// 延迟指定时间 28 | /// 29 | /// 30 | /// 31 | public static CoTaskTimer Delay(TimeSpan span) 32 | { 33 | var timer = CoTaskTimer.Create(); 34 | timer.EndTime = (float)span.TotalSeconds; 35 | return timer; 36 | } 37 | public static async CoTask WaitForFrame(int count = 1) 38 | { 39 | if (count <= 0) 40 | { 41 | await CompletedTask; 42 | } 43 | else 44 | { 45 | var task = CoTaskUpdate.Create(); 46 | task.FrameCount = count; 47 | await task; 48 | } 49 | } 50 | 51 | 52 | private static CoTaskCompleted completedTask = new CoTaskCompleted(); 53 | public static ref CoTaskCompleted CompletedTask => ref completedTask; 54 | 55 | 56 | /// 57 | /// 等待任意一个完成即可 58 | /// 59 | /// 60 | /// 61 | public static CoTask WaitAny(params CoTask[] tasks) 62 | { 63 | //创建计数器 64 | var counterCall = CounterCall.Create(); 65 | counterCall.ClickValue = 1; 66 | counterCall.OnceRecycle = true; 67 | //申请异步任务 68 | var asyncTask = CoTask.Create(); 69 | 70 | //计数器任务绑定 71 | counterCall.OnClick += asyncTask.SetResult; 72 | //绑定异步任务到计数器 73 | foreach (var task in tasks) 74 | { 75 | 76 | task.OnTaskCompleted += counterCall.PlusOne; 77 | task.Discard(); 78 | } 79 | return asyncTask; 80 | } 81 | /// 82 | /// 等待任意一个完成即可 83 | /// 84 | /// 85 | /// 86 | public static CoTask WaitAny(List tasks) 87 | { 88 | //申请计数器 89 | var counterCall = CounterCall.Create(); 90 | //设置触发值 91 | counterCall.ClickValue = 1; 92 | //使用一次就自动回收 93 | counterCall.OnceRecycle = true; 94 | //申请异步任务 95 | var asyncTask = CoTask.Create(); 96 | 97 | //计数器任务绑定,此步骤仅第一次从池申请有GC 98 | counterCall.OnClick += asyncTask.SetResult; 99 | //绑定异步任务到计数器,同样是仅第一次存在GC 100 | foreach (var task in tasks) 101 | { 102 | task.OnTaskCompleted += counterCall.PlusOne; 103 | task.Discard(); 104 | } 105 | return asyncTask; 106 | } 107 | 108 | /// 109 | /// 等待任意一个完成即可 110 | /// 111 | /// 112 | /// 113 | public static CoTask WaitAny(params CoTask[] tasks) 114 | { 115 | //创建计数器 116 | var counterCall = CounterCall.Create(); 117 | counterCall.ClickValue = 1; 118 | counterCall.OnceRecycle = true; 119 | //申请异步任务 120 | var asyncTask = CoTask.Create(); 121 | 122 | //计数器任务绑定 123 | counterCall.OnClick += (x) => { asyncTask.SetResult(x[0]); }; 124 | 125 | //绑定异步任务到计数器 126 | foreach (var task in tasks) 127 | { 128 | task.OnTaskCompleted += counterCall.PlusOne; 129 | task.Discard(); 130 | } 131 | return asyncTask; 132 | } 133 | 134 | /// 135 | /// 等待任意一个完成即可 136 | /// 137 | /// 138 | /// 139 | public static CoTask WaitAny(List> tasks) 140 | { 141 | //创建计数器 142 | var counterCall = CounterCall.Create(); 143 | counterCall.ClickValue = 1; 144 | counterCall.OnceRecycle = true; 145 | //申请异步任务 146 | var asyncTask = CoTask.Create(); 147 | 148 | //计数器任务绑定 149 | counterCall.OnClick += (x) => { asyncTask.SetResult(x[0]); }; 150 | 151 | //绑定异步任务到计数器 152 | foreach (var task in tasks) 153 | { 154 | task.OnTaskCompleted += counterCall.PlusOne; 155 | task.Discard(); 156 | } 157 | return asyncTask; 158 | } 159 | 160 | /// 161 | /// 等待全部完成 162 | /// 163 | /// 164 | /// 165 | public static CoTask WaitAll(params CoTask[] tasks) 166 | { 167 | //申请计数器 168 | var counterCall = CounterCall.Create(); 169 | //设置触发值 170 | counterCall.ClickValue = tasks.Length; 171 | //使用一次就回收 172 | counterCall.OnceRecycle = true; 173 | //申请任务 174 | var asyncTask = CoTask.Create(); 175 | 176 | //绑定结束事件,仅第一次存在GC 177 | counterCall.OnClick += asyncTask.SetResult; 178 | //绑定计数器,仅第一次存在GC 179 | foreach (var task in tasks) 180 | { 181 | task.Discard(); 182 | task.OnTaskCompleted += counterCall.PlusOne; 183 | } 184 | 185 | return asyncTask; 186 | } 187 | 188 | /// 189 | /// 等待全部完成 190 | /// 191 | /// 192 | /// 193 | public static CoTask WaitAll(List tasks) 194 | { 195 | //申请计数器 196 | var counterCall = CounterCall.Create(); 197 | counterCall.ClickValue = tasks.Count; 198 | counterCall.OnceRecycle = true; 199 | //申请任务 200 | var asyncTask = CoTask.Create(); 201 | 202 | //绑定结束事件 203 | counterCall.OnClick += asyncTask.SetResult; 204 | //绑定计数器 205 | foreach (var task in tasks) 206 | { 207 | task.Discard(); 208 | task.OnTaskCompleted += counterCall.PlusOne; 209 | } 210 | 211 | return asyncTask; 212 | } 213 | /// 214 | /// 等待全部完成 215 | /// 216 | /// 217 | /// 218 | public static CoTask WaitAll(params CoTask[] tasks) 219 | { 220 | //申请计数器 221 | var counterCall = CounterCall.Create(); 222 | //设置触发值 223 | counterCall.ClickValue = tasks.Length; 224 | //使用一次就回收 225 | counterCall.OnceRecycle = true; 226 | //申请任务 227 | var asyncTask = CoTask.Create(); 228 | 229 | //绑定结束事件 230 | counterCall.OnClick += (x) => { asyncTask.SetResult(x.ToArray()); }; 231 | //绑定计数器,仅第一次存在GC 232 | foreach (var task in tasks) 233 | { 234 | task.Discard(); 235 | task.OnTaskCompleted += counterCall.PlusOne; 236 | } 237 | 238 | return asyncTask; 239 | } 240 | /// 241 | /// 等待全部完成 242 | /// 243 | /// 244 | /// 245 | public static CoTask WaitAll(List> tasks) 246 | { 247 | //申请计数器 248 | var counterCall = CounterCall.Create(); 249 | //设置触发值 250 | counterCall.ClickValue = tasks.Count; 251 | //使用一次就回收 252 | counterCall.OnceRecycle = true; 253 | //申请任务 254 | var asyncTask = CoTask.Create(); 255 | 256 | //绑定结束事件 257 | counterCall.OnClick += (x) => { asyncTask.SetResult(x.ToArray()); }; 258 | //绑定计数器,仅第一次存在GC 259 | foreach (var task in tasks) 260 | { 261 | task.Discard(); 262 | task.OnTaskCompleted += counterCall.PlusOne; 263 | } 264 | return asyncTask; 265 | } 266 | 267 | 268 | 269 | 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /CoEvent/Runtime/Async/CoTask.cs: -------------------------------------------------------------------------------- 1 | using CoEvents.Async.Internal; 2 | using System; 3 | using System.Diagnostics; 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace CoEvents.Async 7 | { 8 | [AsyncMethodBuilder(typeof(CoTaskBuilder))] 9 | public partial class CoTask : IAsyncTask, IAsyncTokenProperty, ICoTask 10 | { 11 | //在结束时调用,无论是否成功 12 | public event Action OnTaskCompleted = null; 13 | private Action continuation = null; 14 | 15 | 16 | 17 | public bool IsCompleted { get; set; } = false; 18 | //[DebuggerHidden] 19 | public static CoTask Create() 20 | { 21 | CoTask task = null; 22 | if (CoEvent.Pool != null) task = (CoTask)CoEvent.Pool.Allocate(typeof(CoTask)); 23 | else task = new CoTask(); 24 | 25 | task.Token = new AsyncTreeTokenNode(task, task); 26 | task.Token.Current = task; 27 | task.Token.Root = task; 28 | task.IsCompleted = false; 29 | task.Token.Authorization = true; 30 | 31 | return task; 32 | } 33 | //[DebuggerHidden] 34 | public static void Recycle(CoTask task) 35 | { 36 | task.Token.Authorization = false; 37 | 38 | if (CoEvent.Pool != null) return; 39 | CoEvent.Pool?.Recycle(typeof(CoTask), task); 40 | } 41 | 42 | 43 | private Action setResult = null; 44 | public Action SetResult 45 | { 46 | get 47 | { 48 | setResult ??= SetResultMethod; 49 | return setResult; 50 | } 51 | } 52 | 53 | 54 | 55 | #region Token 56 | /// 57 | /// 异步令牌,与AsyncToken作用相同 58 | /// 59 | AsyncTreeTokenNode IAsyncTokenProperty.Token { get => Token; set => Token = value; } 60 | public AsyncTreeTokenNode Token { get; internal set; } 61 | 62 | 63 | 64 | #endregion 65 | 66 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 67 | public void GetResult() { } 68 | 69 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 70 | public void SetException(Exception exception) 71 | { 72 | CoEvent.ExceptionHandler?.Invoke(exception); 73 | SetResultMethod(); 74 | } 75 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 76 | public void SetCancel() 77 | { 78 | SetResultMethod(); 79 | } 80 | //[DebuggerHidden] 81 | private void SetResultMethod() 82 | { 83 | if (Token.Authorization) 84 | { 85 | if (IsCompleted) throw new InvalidOperationException("AsyncTask dont allow SetResult repeatly."); 86 | //执行await以后的代码 87 | continuation?.Invoke(); 88 | continuation = null; 89 | } 90 | IsCompleted = true; 91 | OnTaskCompleted?.Invoke(); 92 | //回收到Pool 93 | Recycle(this); 94 | } 95 | 96 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 97 | public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation); 98 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 99 | public void UnsafeOnCompleted(Action continuation) => this.continuation = continuation; 100 | 101 | 102 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 103 | public CoTask GetAwaiter() => this; 104 | 105 | } 106 | 107 | 108 | [AsyncMethodBuilder(typeof(CoTaskBuilder<>))] 109 | public class CoTask : IAsyncTask, IAsyncTokenProperty, ICoTask 110 | { 111 | //在结束时调用,无论是否成功 112 | public event Action OnTaskCompleted = null; 113 | 114 | 115 | private Action continuation = null; 116 | public bool IsCompleted { get; set; } = false; 117 | public T Result { get; set; } = default; 118 | //[DebuggerHidden] 119 | public static CoTask Create() 120 | { 121 | CoTask task = null; 122 | if (CoEvent.Pool != null) task = (CoTask)CoEvent.Pool.Allocate(typeof(CoTask)); 123 | else task = new CoTask(); 124 | 125 | 126 | task.Token = new AsyncTreeTokenNode(task, task); 127 | task.Token.Current = task; 128 | task.Token.Root = task; 129 | task.IsCompleted = false; 130 | task.Token.Authorization = true; 131 | 132 | return task; 133 | } 134 | //[DebuggerHidden] 135 | public static void Recycle(CoTask task) 136 | { 137 | task.Token.Authorization = false; 138 | task.continuation = null; 139 | if (CoEvent.Pool != null) return; 140 | CoEvent.Pool?.Recycle(typeof(CoTask), task); 141 | } 142 | 143 | 144 | private Action setResult = null; 145 | public Action SetResult 146 | { 147 | get 148 | { 149 | setResult ??= SetResultMethod; 150 | return setResult; 151 | } 152 | } 153 | 154 | 155 | 156 | #region Token 157 | /// 158 | /// 异步令牌,与AsyncToken作用相同 159 | /// 160 | AsyncTreeTokenNode IAsyncTokenProperty.Token { get => Token; set => Token = value; } 161 | public AsyncTreeTokenNode Token { get; internal set; } 162 | 163 | 164 | #endregion 165 | 166 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 167 | public T GetResult() 168 | { 169 | return Result; 170 | } 171 | 172 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 173 | public void SetException(Exception exception) 174 | { 175 | CoEvent.ExceptionHandler?.Invoke(exception); 176 | SetResultMethod(default); 177 | } 178 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 179 | public void SetCancel() 180 | { 181 | 182 | SetResultMethod(default); 183 | } 184 | //[DebuggerHidden] 185 | private void SetResultMethod(T result) 186 | { 187 | if (Token.Authorization) 188 | { 189 | if (IsCompleted) throw new InvalidOperationException("AsyncTask dont allow SetResult repeatly."); 190 | this.Result = result; 191 | //执行await以后的代码 192 | continuation?.Invoke(); 193 | continuation = null; 194 | } 195 | IsCompleted = true; 196 | OnTaskCompleted?.Invoke(Result); 197 | //回收到Pool 198 | Recycle(this); 199 | } 200 | 201 | private Action unsafeSetResult = null; 202 | public Action UnsafeSetResult 203 | { 204 | get 205 | { 206 | if (unsafeSetResult == null) 207 | { 208 | unsafeSetResult = UnsafeSetResultMethod; 209 | } 210 | return unsafeSetResult; 211 | } 212 | } 213 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 214 | private void UnsafeSetResultMethod() 215 | { 216 | SetResult(this.Result); 217 | } 218 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 219 | public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation); 220 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 221 | public void UnsafeOnCompleted(Action continuation) => this.continuation = continuation; 222 | 223 | 224 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 225 | public CoTask GetAwaiter() => this; 226 | 227 | } 228 | 229 | 230 | public class CoTaskTimer : IAsyncTask, IAsyncTokenProperty, ICoTask 231 | { 232 | private Action continuation = null; 233 | public bool IsCompleted { get; set; } = false; 234 | //[DebuggerHidden] 235 | public static CoTaskTimer Create() 236 | { 237 | CoTaskTimer task = null; 238 | if (CoEvent.Pool != null) task = (CoTaskTimer)CoEvent.Pool.Allocate(typeof(CoTaskTimer)); 239 | else task = new CoTaskTimer(); 240 | 241 | task.Token = new AsyncTreeTokenNode(task, task); 242 | task.Token.Current = task; 243 | task.Token.Root = task; 244 | task.IsCompleted = false; 245 | task.currentTime = 0; 246 | task.EndTime = 1000f; 247 | task.Token.Authorization = true; 248 | 249 | 250 | 251 | return task; 252 | } 253 | //[DebuggerHidden] 254 | public static void Recycle(CoTaskTimer task) 255 | { 256 | task.Token.Authorization = false; 257 | task.continuation = null; 258 | //CoEvent.Instance.Operator().UnSubscribe(task.Update); 259 | if (CoEvent.Pool != null) return; 260 | CoEvent.Pool?.Recycle(typeof(CoTask), task); 261 | } 262 | 263 | 264 | private Action setResult = null; 265 | //[DebuggerHidden] 266 | public Action SetResult 267 | { 268 | get 269 | { 270 | setResult ??= SetResultMethod; 271 | return setResult; 272 | } 273 | } 274 | 275 | 276 | 277 | #region Token 278 | /// 279 | /// 异步令牌,与AsyncToken作用相同 280 | /// 281 | //[DebuggerHidden] 282 | AsyncTreeTokenNode IAsyncTokenProperty.Token { get => Token; set => Token = value; } 283 | //[DebuggerHidden] 284 | public AsyncTreeTokenNode Token { get; internal set; } 285 | 286 | 287 | 288 | #endregion 289 | 290 | 291 | public float EndTime { get; set; } = 1000f; 292 | private float currentTime = 0f; 293 | void Update(float deltaTime) 294 | { 295 | //UnityEngine.Debug.Log(Token.Authorization); 296 | if (Token.Authorization) 297 | { 298 | currentTime += deltaTime; 299 | if (currentTime >= EndTime) 300 | { 301 | SetResult(); 302 | } 303 | } 304 | } 305 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 306 | public void GetResult() { } 307 | 308 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 309 | public void SetException(Exception exception) 310 | { 311 | CoEvent.ExceptionHandler?.Invoke(exception); 312 | SetResultMethod(); 313 | } 314 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 315 | public void SetCancel() 316 | { 317 | SetResultMethod(); 318 | } 319 | //[DebuggerHidden] 320 | private void SetResultMethod() 321 | { 322 | if (Token.Authorization) 323 | { 324 | //执行await以后的代码 325 | continuation?.Invoke(); 326 | } 327 | CoEvent.Instance.Operator().UnSubscribe(Update); 328 | //回收到Pool 329 | Recycle(this); 330 | } 331 | 332 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 333 | public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation); 334 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 335 | public void UnsafeOnCompleted(Action continuation) => this.continuation = continuation; 336 | 337 | 338 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 339 | public CoTaskTimer GetAwaiter() 340 | { 341 | CoEvent.Instance.Operator().Subscribe(Update); 342 | return this; 343 | } 344 | } 345 | 346 | public class CoTaskUpdate : IAsyncTask, IAsyncTokenProperty, ICoTask 347 | { 348 | //在结束时调用,无论是否成功 349 | public event Action OnTaskCompleted = null; 350 | 351 | 352 | private Action continuation = null; 353 | public bool IsCompleted { get; set; } = false; 354 | //[DebuggerHidden] 355 | public static CoTaskUpdate Create() 356 | { 357 | CoTaskUpdate task = null; 358 | if (CoEvent.Pool != null) task = (CoTaskUpdate)CoEvent.Pool.Allocate(typeof(CoTaskUpdate)); 359 | else task = new CoTaskUpdate(); 360 | 361 | task.Token = new AsyncTreeTokenNode(task, task); 362 | task.Token.Current = task; 363 | task.Token.Root = task; 364 | task.IsCompleted = false; 365 | task.FrameCount = 1; 366 | task.current = 0; 367 | task.Token.Authorization = true; 368 | 369 | CoEvent.Instance.Operator().Subscribe(task.Update); 370 | 371 | return task; 372 | } 373 | //[DebuggerHidden] 374 | public static void Recycle(CoTaskUpdate task) 375 | { 376 | task.Token.Authorization = false; 377 | task.continuation = null; 378 | CoEvent.Instance.Operator().UnSubscribe(task.Update); 379 | if (CoEvent.Pool != null) return; 380 | CoEvent.Pool?.Recycle(typeof(CoTaskUpdate), task); 381 | } 382 | 383 | 384 | private Action setResult = null; 385 | public Action SetResult 386 | { 387 | get 388 | { 389 | setResult ??= SetResultMethod; 390 | return setResult; 391 | } 392 | } 393 | 394 | 395 | 396 | #region Token 397 | /// 398 | /// 异步令牌,与AsyncToken作用相同 399 | /// 400 | AsyncTreeTokenNode IAsyncTokenProperty.Token { get => Token; set => Token = value; } 401 | public AsyncTreeTokenNode Token { get; internal set; } 402 | 403 | 404 | 405 | #endregion 406 | 407 | 408 | public int FrameCount { get; set; } = 1; 409 | int current = 0; 410 | 411 | void Update(float deltaTime) 412 | { 413 | if (Token.Authorization) 414 | if (current++ >= FrameCount) 415 | { 416 | SetResult(); 417 | } 418 | 419 | } 420 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 421 | public void GetResult() { } 422 | 423 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 424 | public void SetException(Exception exception) 425 | { 426 | CoEvent.ExceptionHandler?.Invoke(exception); 427 | SetResultMethod(); 428 | } 429 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 430 | public void SetCancel() 431 | { 432 | 433 | SetResultMethod(); 434 | } 435 | //[DebuggerHidden] 436 | private void SetResultMethod() 437 | { 438 | if (Token.Authorization) 439 | { 440 | if (IsCompleted) throw new InvalidOperationException("AsyncTask dont allow SetResult repeatly."); 441 | //执行await以后的代码 442 | continuation?.Invoke(); 443 | continuation = null; 444 | } 445 | IsCompleted = true; 446 | OnTaskCompleted?.Invoke(); 447 | //回收到Pool 448 | Recycle(this); 449 | } 450 | 451 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 452 | public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation); 453 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 454 | public void UnsafeOnCompleted(Action continuation) => this.continuation = continuation; 455 | 456 | 457 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 458 | public CoTaskUpdate GetAwaiter() => this; 459 | 460 | } 461 | 462 | 463 | public struct CoTaskCompleted : INotifyCompletion, ICoTask 464 | { 465 | 466 | public bool IsCompleted => true; 467 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 468 | public void GetResult() { } 469 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 470 | public void SetException(Exception exception) 471 | { 472 | CoEvent.ExceptionHandler?.Invoke(exception); 473 | } 474 | 475 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 476 | public CoTaskCompleted GetAwaiter() => this; 477 | [DebuggerHidden, MethodImpl(MethodImplOptions.AggressiveInlining)] 478 | public void OnCompleted(Action continuation) { } 479 | } 480 | } 481 | --------------------------------------------------------------------------------