移除了中断相关的后台代码与UI交互(待重写);重写运行时节点获取参数的方法;重写了节点容器的互动;完善了WebSocket远程交互;完善了项目文件的加载;

This commit is contained in:
fengjiayi
2024-12-26 16:42:05 +08:00
parent 56b22be8c0
commit 7a6f8c407b
37 changed files with 880 additions and 1127 deletions

View File

@@ -1,4 +1,5 @@
using Serein.Library;
using Serein.Library.Utils;
namespace Serein.Library.Api

View File

@@ -6,7 +6,6 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using static Serein.Library.Utils.ChannelFlowInterrupt;
namespace Serein.Library.Api
{
@@ -203,7 +202,7 @@ namespace Serein.Library.Api
/// <summary>
/// 移除
/// </summary>
Remote,
Remove,
}
/// <summary>
@@ -311,9 +310,9 @@ namespace Serein.Library.Api
//}
/// <summary>
/// 节点Model对象,目前需要手动转换对应的类型
/// 节点Model对象
/// </summary>
public object NodeModel { get; private set; }
public NodeModelBase NodeModel { get; private set; }
public PositionOfUI Position { get; private set; }
//public bool IsAddInRegion { get; private set; }
public string RegeionGuid { get; private set; }
@@ -934,13 +933,17 @@ namespace Serein.Library.Api
void TerminateFlipflopNode(string nodeGuid);
/// <summary>
#region
#if false
/// <summary>
/// 设置节点中断
/// </summary>
/// <param name="nodeGuid">更改中断状态的节点Guid</param>
/// <param name="isInterrup">是否中断</param>
/// <returns></returns>
Task<bool> SetNodeInterruptAsync(string nodeGuid,bool isInterrup);
Task<bool> SetNodeInterruptAsync(string nodeGuid, bool isInterrup);
/// <summary>
/// 添加作用于某个对象的中断表达式
@@ -955,7 +958,7 @@ namespace Serein.Library.Api
/// </summary>
/// <param name="key">需要监视的对象</param>
/// <param name="isMonitor">是否启用监视</param>
void SetMonitorObjState(string key,bool isMonitor);
void SetMonitorObjState(string key, bool isMonitor);
/// <summary>
/// 检查一个对象是否处于监听状态如果是则传出与该对象相关的表达式用于中断如果不是则返回false。
@@ -971,7 +974,9 @@ namespace Serein.Library.Api
/// <param name="signal"></param>
/// <param name="interruptClass"></param>
/// <returns></returns>
Task<CancelType> GetOrCreateGlobalInterruptAsync();
Task<CancelType> InterruptNode();
#endif
#endregion
/// <summary>
/// (用于远程)通知节点属性变更

View File

@@ -1,11 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Serein.Library.Utils;
using System;
using System.Threading.Tasks;
namespace Serein.Library.Api
{
/// <summary>
/// 触发器接口
/// </summary>

View File

@@ -15,13 +15,13 @@ namespace Serein.Library.Api
/// 放置一个节点
/// </summary>
/// <param name="nodeModel"></param>
void PlaceNode(NodeModelBase nodeModel);
bool PlaceNode(NodeModelBase nodeModel);
/// <summary>
/// 取出一个节点
/// </summary>
/// <param name="nodeModel"></param>
void TakeOutNode(NodeModelBase nodeModel);
bool TakeOutNode(NodeModelBase nodeModel);
/// <summary>
/// 取出所有节点(用于删除容器)

View File

@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using static Serein.Library.Utils.ChannelFlowInterrupt;
namespace Serein.Library
{
@@ -42,7 +41,7 @@ namespace Serein.Library
/// <summary>
/// 中断级别,暂时停止继续执行后继分支。
/// </summary>
[PropertyInfo(IsNotification = true, CustomCodeAtEnd = "NodeModel?.Env?.SetNodeInterruptAsync(NodeModel?.Guid, value);")] // CustomCode = "NodeModel?.Env?.SetNodeInterruptAsync(NodeModel?.Guid, value);"
[PropertyInfo(IsNotification = true, CustomCodeAtEnd = "// NodeModel?.Env?.SetNodeInterruptAsync(NodeModel?.Guid, value);")] // CustomCode = "NodeModel?.Env?.SetNodeInterruptAsync(NodeModel?.Guid, value);"
private bool _isInterrupt = false;
/// <summary>
@@ -55,7 +54,7 @@ namespace Serein.Library
/// 中断Task用来中断
/// </summary>
[PropertyInfo]
private Func<Task<CancelType>> _getInterruptTask;
private Func<Task> _getInterruptTask;
}

View File

@@ -16,7 +16,6 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static Serein.Library.Utils.ChannelFlowInterrupt;
namespace Serein.Library
{
@@ -366,16 +365,15 @@ namespace Serein.Library
/// <returns>节点传回数据对象</returns>
public virtual async Task<object> ExecutingAsync(IDynamicContext context)
{
if(context.NextOrientation == ConnectionInvokeType.IsError)
{
Console.WriteLine("");
}
//if(context.NextOrientation == ConnectionInvokeType.IsError)
//{
//}
#region
if (DebugSetting.IsInterrupt) // 执行触发检查是否需要中断
{
var cancelType = await this.DebugSetting.GetInterruptTask(); // 等待中断结束
await Console.Out.WriteLineAsync($"[{this.MethodDetails?.MethodName}]中断已{cancelType},开始执行后继分支");
//var cancelType = await this.DebugSetting.GetInterruptTask(); // 等待中断结束
await Console.Out.WriteLineAsync($"[{this.MethodDetails?.MethodName}]中断已取消,开始执行后继分支");
}
#endregion
@@ -394,7 +392,7 @@ namespace Serein.Library
md.ActingInstance = context.Env.IOC.Get(md.ActingInstanceType);
}
object[] args = await GetParametersAsync(context, this);
object[] args = await GetParametersAsync(context);
var result = await dd.InvokeAsync(md.ActingInstance, args);
return result;
@@ -403,296 +401,50 @@ namespace Serein.Library
/// <summary>
/// 获取对应的参数数组
/// </summary>
public static async Task<object[]> GetParametersAsync(IDynamicContext context,
NodeModelBase nodeModel)
public async Task<object[]> GetParametersAsync(IDynamicContext context)
{
// 用正确的大小初始化参数数组
var md = nodeModel.MethodDetails;
if (md.ParameterDetailss.Length == 0)
if (MethodDetails.ParameterDetailss.Length == 0)
{
return null;// md.ActingInstance
return new object[0];// md.ActingInstance
}
object[] parameters;
object[] args;
Array paramsArgs = null; // 初始化可选参数
int paramsArgIndex = 0; // 可选参数下标,与 object[] paramsArgs 一起使用
if (md.ParamsArgIndex >= 0)
if (MethodDetails.ParamsArgIndex >= 0) // 存在可变入参参数
{
// 存在可变入参参数
var paramsArgType = md.ParameterDetailss[md.ParamsArgIndex].DataType; // 获取可变参数的参数类型
// 可变参数数组长度 = 方法参数个数 - 可选入参下标 + 1
int paramsLength = md.ParameterDetailss.Length - md.ParamsArgIndex;
var paramsArgType = MethodDetails.ParameterDetailss[MethodDetails.ParamsArgIndex].DataType; // 获取可变参数的参数类型
int paramsLength = MethodDetails.ParameterDetailss.Length - MethodDetails.ParamsArgIndex; // 可变参数数组长度 = 方法参数个数 - 可选入参下标 + 1
paramsArgs = Array.CreateInstance(paramsArgType, paramsLength);// 可变参数
parameters = new object[md.ParamsArgIndex+1]; // 调用方法的入参数组
parameters[md.ParamsArgIndex] = paramsArgs; // 如果存在可选参数,入参参数最后一项则为可变参数
args = new object[MethodDetails.ParamsArgIndex + 1]; // 调用方法的入参数组
args[MethodDetails.ParamsArgIndex] = paramsArgs; // 如果存在可选参数,入参参数最后一项则为可变参数
}
else
{
// 不存在可选参数
parameters = new object[md.ParameterDetailss.Length]; // 调用方法的入参数组
args = new object[MethodDetails.ParameterDetailss.Length]; // 调用方法的入参数组
}
bool hasParams = false;
for (int i = 0; i < md.ParameterDetailss.Length; i++)
for (int i = 0; i < args.Length; i++) {
var pd = MethodDetails.ParameterDetailss[i];
args[i] = await pd.ToMethodArgData(context); // 获取数据
}
if(MethodDetails.ParamsArgIndex >= 0)
{
var pd = md.ParameterDetailss[i]; // 方法入参描述
var argDataType = pd.DataType;
// 入参参数下标循环到可选参数时,开始写入到可选参数数组
if (paramsArgs != null && i >= md.ParamsArgIndex)
for (int i = 0; i < paramsArgs.Length; i++)
{
// 控制参数赋值方向:
// true => paramsArgs
// false => parameters
hasParams = true;
var pd = MethodDetails.ParameterDetailss[paramsArgIndex + i];
var data = await pd.ToMethodArgData(context); // 获取数据
paramsArgs.SetValue(data, i);// 设置到数组中
}
#region
if (argDataType == typeof(IFlowEnvironment)) // 获取流程上下文
{
parameters[i] = nodeModel.Env;
continue;
}
if (argDataType == typeof(IDynamicContext)) // 获取流程上下文
{
parameters[i] = context;
continue;
}
#endregion
#region []
object inputParameter; // 存放解析的临时参数
if (pd.IsExplicitData && !pd.DataValue.StartsWith("@", StringComparison.OrdinalIgnoreCase)) // 判断是否使用显示的输入参数
{
// 使用输入的固定值
inputParameter = pd.DataValue;
}
else
{
#region
if (pd.ArgDataSourceType == ConnectionArgSourceType.GetPreviousNodeData)
{
var previousNode = context.GetPreviousNode(nodeModel);
if (previousNode is null)
{
inputParameter = null;
}
else
{
inputParameter = context.GetFlowData(previousNode.Guid); // 当前传递的数据
}
}
#endregion
#region
else if (pd.ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeData)
{
// 获取指定节点的数据
// 如果指定节点没有被执行会返回null
// 如果执行过,会获取上一次执行结果作为预入参数据
inputParameter = context.GetFlowData(pd.ArgDataSourceNodeGuid);
}
#endregion
#region
else if (pd.ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeDataOfInvoke)
{
// 立刻调用对应节点获取数据。
try
{
var result = await context.Env.InvokeNodeAsync(context, pd.ArgDataSourceNodeGuid);
inputParameter = result;
}
catch (Exception ex)
{
context.NextOrientation = ConnectionInvokeType.IsError;
context.ExceptionOfRuning = ex;
throw;
}
}
#endregion
#region
else
{
throw new Exception("节点执行方法获取入参参数时ConnectionArgSourceType枚举是意外的枚举值");
}
#endregion
}
#region @Get / @DTC Data type conversion / @Data ()
if (pd.IsExplicitData)
{
// @Get 表达式 (从上一节点获取对象)
if (pd.DataValue.StartsWith("@get", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(pd.DataValue, inputParameter, out _);
}
// @DTC 表达式 Data type conversion
if (pd.DataValue.StartsWith("@dtc", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(pd.DataValue, inputParameter, out _);
}
// @Data 表达式 (获取全局数据)
if (pd.DataValue.StartsWith("@data", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(pd.DataValue, inputParameter, out _);
}
}
#endregion
#region null检查
if (!argDataType.IsValueType && inputParameter is null)
{
parameters[i] = null;
throw new Exception($"[arg{pd.Index}][{pd.Name}][{argDataType}]参数不能为null");
continue;
}
#endregion
#endregion
//#region 入参存在取值转换器调用对应的转换器获取入参数据如果获取成功不为null会跳过循环
//if (pd.ExplicitType.IsEnum && !(pd.Convertor is null))
//{
// //var resultEnum = Enum.ToObject(ed.ExplicitType, ed.DataValue);
// var resultEnum = Enum.Parse(pd.ExplicitType, pd.DataValue);
// var value = pd.Convertor(resultEnum);
// if (value is null)
// {
// throw new InvalidOperationException("转换器调用失败");
// }
// else
// {
// if (hasParams)
// {
// paramsArgs.SetValue(value, paramsArgIndex++);
// // 处理可选参数
// //paramsArgs[paramsArgIndex++] = value;
// }
// else
// {
// parameters[i] = value;
// }
// continue;
// }
//}
//#endregion
#region BinValue的类型转换器null
// 入参存在基于BinValue的类型转换器获取枚举转换器中记录的类型
if (pd.ExplicitType.IsEnum && argDataType != pd.ExplicitType)
{
var resultEnum = Enum.Parse(pd.ExplicitType, pd.DataValue);
// 获取绑定的类型
var type = EnumHelper.GetBoundValue(pd.ExplicitType, resultEnum, attr => attr.Value);
if (type is Type enumBindType && !(enumBindType is null))
{
var value = nodeModel.Env.IOC.Instantiate(enumBindType);
if (value is null)
{
}
else
{
if (hasParams)
{
// 处理可选参数
paramsArgs.SetValue(value, paramsArgIndex++);
//paramsArgs[paramsArgIndex++] = value;
}
else
{
parameters[i] = value;
}
continue;
}
}
}
#endregion
#region
object tmpVaue = null; // 临时存放数据,最后才判断是否放置可选参数数组
var inputParameterType = inputParameter.GetType();
if (inputParameterType == argDataType)
{
tmpVaue = inputParameter; // 类型一致无需转换,直接装入入参数组
}
else if (argDataType.IsValueType)
{
// 值类型
var valueStr = inputParameter?.ToString();
tmpVaue = valueStr.ToValueData(argDataType); // 类型不一致,尝试进行转换,如果转换失败返回类型对应的默认值
}
else
{
// 引用类型
if (argDataType == typeof(string)) // 转为字符串
{
var valueStr = inputParameter?.ToString();
tmpVaue = valueStr;
}
else if(argDataType.IsSubclassOf(inputParameterType)) // 入参类型 是 预入参数据类型 的 子类/实现类
{
// 方法入参中,父类不能隐式转为子类,这里需要进行强制转换
tmpVaue = ObjectConvertHelper.ConvertParentToChild(inputParameter, argDataType);
}
else if(argDataType.IsAssignableFrom(inputParameterType)) // 入参类型 是 预入参数据类型 的 父类/接口
{
tmpVaue = inputParameter;
}
// 集合类型
//else if(inputParameter is IEnumerable collection)
//{
// var enumerableMethods = typeof(Enumerable).GetMethods(); // 获取所有的 Enumerable 扩展方法
// MethodInfo conversionMethod;
// if (argDataType.IsArray) // 转为数组
// {
// parameters[i] = inputParameter;
// conversionMethod = enumerableMethods.FirstOrDefault(m => m.Name == "ToArray" && m.IsGenericMethodDefinition);
// }
// else if (argDataType.GetGenericTypeDefinition() == typeof(List<>)) // 转为集合
// {
// conversionMethod = enumerableMethods.FirstOrDefault(m => m.Name == "ToList" && m.IsGenericMethodDefinition);
// }
// else
// {
// throw new InvalidOperationException("输入对象不是集合或目标类型不支持目前仅支持Array、List的自动转换");
// }
// var genericMethod = conversionMethod.MakeGenericMethod(argDataType);
// var result = genericMethod.Invoke(null, new object[] { collection });
// parameters[i] = result;
//}
}
if (hasParams)
{
// 处理可选参数
paramsArgs.SetValue(tmpVaue, paramsArgIndex++);
//paramsArgs[paramsArgIndex++] = tmpVaue;
}
else
{
parameters[i] = tmpVaue;
}
#endregion
args[args.Length - 1] = paramsArgs;
}
return parameters;
return args;
}
/// <summary>
/// 更新节点数据,并检查监视表达式是否生效
/// </summary>
@@ -733,37 +485,37 @@ namespace Serein.Library
{
return;
}
(var isMonitor, var exps) = await context.Env.CheckObjMonitorStateAsync(key);
if (isMonitor) // 如果新的数据处于查看状态通知UI进行更新交给运行环境判断
{
context.Env.MonitorObjectNotification(nodeModel.Guid, data, sourceType); // 对象处于监视状态通知UI更新数据显示
if (exps.Length > 0)
{
// 表达式环境下判断是否需要执行中断
bool isExpInterrupt = false;
string exp = "";
// 判断执行监视表达式,直到为 true 时退出
for (int i = 0; i < exps.Length && !isExpInterrupt; i++)
{
exp = exps[i];
if (string.IsNullOrEmpty(exp)) continue;
// isExpInterrupt = SereinConditionParser.To(data, exp);
}
//(var isMonitor, var exps) = await context.Env.CheckObjMonitorStateAsync(key);
//if (isMonitor) // 如果新的数据处于查看状态通知UI进行更新交给运行环境判断
//{
// context.Env.MonitorObjectNotification(nodeModel.Guid, data, sourceType); // 对象处于监视状态通知UI更新数据显示
// if (exps.Length > 0)
// {
// // 表达式环境下判断是否需要执行中断
// bool isExpInterrupt = false;
// string exp = "";
// // 判断执行监视表达式,直到为 true 时退出
// for (int i = 0; i < exps.Length && !isExpInterrupt; i++)
// {
// exp = exps[i];
// if (string.IsNullOrEmpty(exp)) continue;
// // isExpInterrupt = SereinConditionParser.To(data, exp);
// }
if (isExpInterrupt) // 触发中断
{
nodeModel.DebugSetting.IsInterrupt = true;
if (await context.Env.SetNodeInterruptAsync(nodeModel.Guid,true))
{
context.Env.TriggerInterrupt(nodeModel.Guid, exp, InterruptTriggerEventArgs.InterruptTriggerType.Exp);
var cancelType = await nodeModel.DebugSetting.GetInterruptTask();
await Console.Out.WriteLineAsync($"[{data}]中断已{cancelType},开始执行后继分支");
nodeModel.DebugSetting.IsInterrupt = false;
}
}
}
// if (isExpInterrupt) // 触发中断
// {
// nodeModel.DebugSetting.IsInterrupt = true;
// if (await context.Env.SetNodeInterruptAsync(nodeModel.Guid,true))
// {
// context.Env.TriggerInterrupt(nodeModel.Guid, exp, InterruptTriggerEventArgs.InterruptTriggerType.Exp);
// var cancelType = await nodeModel.DebugSetting.GetInterruptTask();
// await Console.Out.WriteLineAsync($"[{data}]中断已{cancelType},开始执行后继分支");
// nodeModel.DebugSetting.IsInterrupt = false;
// }
// }
// }
}
//}
}
///// <summary>

View File

@@ -1,8 +1,11 @@
using Serein.Library.Api;
using Serein.Library.Utils;
using Serein.Library.Utils.SereinExpression;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Serein.Library
{
@@ -111,7 +114,6 @@ namespace Serein.Library
{
}
/// <summary>
/// 为节点实例化新的入参描述
@@ -178,6 +180,141 @@ namespace Serein.Library
return pd;
}
/// <summary>
/// 转为方法入参数据
/// </summary>
/// <returns></returns>
public async ValueTask<object> ToMethodArgData(IDynamicContext context)
{
var nodeModel = NodeModel;
var env = nodeModel.Env;
#region
// 返回运行环境
if (DataType == typeof(IFlowEnvironment))
{
return env;
}
// 返回流程上下文
if (DataType == typeof(IDynamicContext))
{
return context;
}
// 显式设置的参数
if (IsExplicitData && !DataValue.StartsWith("@", StringComparison.OrdinalIgnoreCase))
{
return DataValue.ToConvert(DataType); // 并非表达式,同时是显式设置的参数
}
#endregion
#region -
if (ExplicitType.IsEnum && DataType != ExplicitType)
{
var resultEnum = Enum.Parse(ExplicitType, DataValue);
// 获取绑定的类型
var type = EnumHelper.GetBoundValue(ExplicitType, resultEnum, attr => attr.Value);
if (type is Type enumBindType && !(enumBindType is null))
{
var value = nodeModel.Env.IOC.Instantiate(enumBindType);
return value;
}
}
#endregion
// 需要获取预入参数据
object inputParameter;
#region
if (ArgDataSourceType == ConnectionArgSourceType.GetPreviousNodeData)
{
var previousNode = context.GetPreviousNode(nodeModel);
if (previousNode is null)
{
inputParameter = null;
}
else
{
inputParameter = context.GetFlowData(previousNode.Guid); // 当前传递的数据
}
}
#endregion
#region
else if (ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeData)
{
// 获取指定节点的数据
// 如果指定节点没有被执行会返回null
// 如果执行过,会获取上一次执行结果作为预入参数据
inputParameter = context.GetFlowData(ArgDataSourceNodeGuid);
}
#endregion
#region
else if (ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeDataOfInvoke)
{
// 立刻调用对应节点获取数据。
try
{
var result = await env.InvokeNodeAsync(context, ArgDataSourceNodeGuid);
inputParameter = result;
}
catch (Exception ex)
{
context.NextOrientation = ConnectionInvokeType.IsError;
context.ExceptionOfRuning = ex;
throw;
}
}
#endregion
#region
else
{
throw new Exception("节点执行方法获取入参参数时ConnectionArgSourceType枚举是意外的枚举值");
}
#endregion
#region
if (IsExplicitData)
{
// @Get 表达式 (从上一节点获取对象)
if (DataValue.StartsWith("@get", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(DataValue, inputParameter, out _);
}
// @DTC 表达式 Data type conversion
else if (DataValue.StartsWith("@dtc", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(DataValue, inputParameter, out _);
}
// @Data 表达式 (获取全局数据)
else if (DataValue.StartsWith("@data", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(DataValue, inputParameter, out _);
}
}
#endregion
// 对引用类型检查 null
if (!DataType.IsValueType && inputParameter is null)
{
throw new Exception($"[arg{Index}][{Name}][{DataType}]参数不能为null");
}
if (DataType == typeof(string)) // 转为字符串
{
return inputParameter.ToString();
}
var inputParameterType = inputParameter.GetType();
if (DataType.IsSubclassOf(inputParameterType)) // 入参类型 是 预入参数据类型 的 子类/实现类
{
// 方法入参中,父类不能隐式转为子类,这里需要进行强制转换
return ObjectConvertHelper.ConvertParentToChild(inputParameter, DataType);
}
if (DataType.IsAssignableFrom(inputParameterType)) // 入参类型 是 预入参数据类型 的 父类/接口
{
return inputParameter;
}
throw new Exception($"[arg{Index}][{Name}][{DataType}]入参类型不符合,当前预入参类型为{inputParameterType}");
}
public override string ToString()
{
return $"[{this.Index}] {this.Name} : {this.ExplicitType?.FullName} -> {this.DataType?.FullName}";

View File

@@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace Serein.Library.Network.WebSocketCommunication.Handle
{
/// <summary>
/// 表示参数可以为空(Net462不能使用NutNull的情况
/// 表示参数不能为空(Net462不能使用NutNull的情况
/// </summary>
public sealed class NeedfulAttribute : Attribute
{

View File

@@ -38,6 +38,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Reactive" Version="6.0.1" />
<PackageReference Include="System.Threading.Channels" Version="8.0.0" />

View File

@@ -1,353 +0,0 @@
#region plan 2
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Serein.Library.Utils
{
/// <summary>
/// 流程中断管理
/// </summary>
public class ChannelFlowInterrupt
{
/// <summary>
/// 中断取消类型
/// </summary>
public enum CancelType
{
Manual,
Error,
Overtime
}
// 使用并发字典管理每个信号对应的 Channel
private readonly ConcurrentDictionary<string, Channel<CancelType>> _channels = new ConcurrentDictionary<string, Channel<CancelType>>();
/// <summary>
/// 创建信号并指定超时时间,到期后自动触发(异步方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="outTime">超时时间</param>
/// <returns>等待任务</returns>
public async Task<CancelType> GetCreateChannelWithTimeoutAsync(string signal, TimeSpan outTime)
{
var channel = GetOrCreateChannel(signal);
var cts = new CancellationTokenSource();
// 异步任务:超时后自动触发信号
_ = Task.Run(async () =>
{
try
{
await Task.Delay(outTime, cts.Token);
if (!cts.Token.IsCancellationRequested)
{
await channel.Writer.WriteAsync(CancelType.Overtime);
}
}
catch (OperationCanceledException)
{
// 超时任务被取消
}
finally
{
cts?.Dispose();
}
}, cts.Token);
// 等待信号传入(超时或手动触发)
try
{
var result = await channel.Reader.ReadAsync();
return result;
}
catch
{
return CancelType.Error;
}
}
/// <summary>
/// 创建信号,直到手动触发(异步方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <returns>等待任务</returns>
public async Task<CancelType> GetOrCreateChannelAsync(string signal)
{
try
{
var channel = GetOrCreateChannel(signal);
// 等待信号传入(超时或手动触发)
var result = await channel.Reader.ReadAsync();
return result;
}
catch
{
return CancelType.Manual;
}
}
/// <summary>
/// 创建信号并指定超时时间,到期后自动触发(同步阻塞方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="timeout">超时时间</param>
public async Task<CancelType> CreateChannelWithTimeoutSync(string signal, TimeSpan timeout)
{
var channel = GetOrCreateChannel(signal);
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
// 异步任务:超时后自动触发信号
_ = Task.Run(async () =>
{
try
{
await Task.Delay(timeout, token);
await channel.Writer.WriteAsync(CancelType.Overtime);
}
catch (OperationCanceledException ex)
{
// 任务被取消
await Console.Out.WriteLineAsync(ex.Message);
}
});
// 同步阻塞直到信号触发或超时
var result = await channel.Reader.ReadAsync();
return result;
}
/// <summary>
/// 触发信号
/// </summary>
/// <param name="signal">信号字符串</param>
/// <returns>是否成功触发</returns>
public bool TriggerSignal(string signal)
{
//if (_channels.TryGetValue(signal, out var channel))
//{
// // 手动触发信号
// channel.Writer.TryWrite(CancelType.Manual);
// return true;
//}
//return false;
try
{
if (_channels.TryGetValue(signal, out var channel))
{
// 手动触发信号
channel.Writer.TryWrite(CancelType.Manual);
// 完成写入,标记该信号通道不再接受新写入
channel.Writer.Complete();
// 触发后移除信号
_channels.TryRemove(signal, out _);
return true;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// 取消所有任务
/// </summary>
public void CancelAllTasks()
{
foreach (var channel in _channels.Values)
{
try
{
channel.Writer.Complete();
}
finally
{
}
}
_channels.Clear();
}
/// <summary>
/// 获取或创建指定信号的 Channel
/// </summary>
/// <param name="signal">信号字符串</param>
/// <returns>对应的 Channel</returns>
private Channel<CancelType> GetOrCreateChannel(string signal)
{
return _channels.GetOrAdd(signal, _ => Channel.CreateUnbounded<CancelType>());
}
}
}
#endregion
#region plan 3
//using System;
//using System.Collections.Concurrent;
//using System.Threading;
//using System.Threading.Channels;
//using System.Threading.Tasks;
//namespace Serein.Library.Utils
//{
// /// <summary>
// /// 流程中断管理类,提供了基于 Channel 的异步中断机制
// /// </summary>
// public class ChannelFlowInterrupt
// {
// /// <summary>
// /// 中断取消类型
// /// </summary>
// public enum CancelType
// {
// Manual, // 手动触发
// Overtime, // 超时触发
// Discard // 丢弃触发
// }
// // 使用并发字典管理每个信号对应的 Channel 和状态
// private readonly ConcurrentDictionary<string, (Channel<CancelType> Channel, bool IsCancelled, bool IsDiscardMode)> _channels
// = new ConcurrentDictionary<string, (Channel<CancelType>, bool, bool)>();
// // 锁对象,用于保护并发访问
// private readonly object _lock = new object();
// /// <summary>
// /// 创建带有超时功能的信号,超时后自动触发
// /// </summary>
// public async Task<CancelType> GetCreateChannelWithTimeoutAsync(string signal, TimeSpan outTime)
// {
// var (channel, isCancelled, isDiscardMode) = GetOrCreateChannel(signal);
// // 如果信号已取消或在丢弃模式下,立即返回丢弃类型
// if (isCancelled || isDiscardMode) return CancelType.Discard;
// var cts = new CancellationTokenSource();
// _ = Task.Run(async () =>
// {
// try
// {
// await Task.Delay(outTime, cts.Token);
// if (!cts.Token.IsCancellationRequested && !isCancelled)
// {
// await channel.Writer.WriteAsync(CancelType.Overtime);
// }
// }
// catch (OperationCanceledException)
// {
// // 处理任务取消的情况
// }
// finally
// {
// cts.Dispose();
// }
// }, cts.Token);
// return await channel.Reader.ReadAsync();
// }
// /// <summary>
// /// 创建或获取现有信号,等待手动触发
// /// </summary>
// public async Task<CancelType> GetOrCreateChannelAsync(string signal)
// {
// var (channel, isCancelled, isDiscardMode) = GetOrCreateChannel(signal);
// // 如果信号已取消或在丢弃模式下,立即返回丢弃类型
// if (isCancelled || isDiscardMode) return CancelType.Discard;
// return await channel.Reader.ReadAsync();
// }
// /// <summary>
// /// 触发信号并将其移除
// /// </summary>
// public bool TriggerSignal(string signal)
// {
// lock (_lock)
// {
// if (_channels.TryGetValue(signal, out var channelInfo))
// {
// var (channel, isCancelled, isDiscardMode) = channelInfo;
// // 如果信号未被取消,则触发并标记为已取消
// if (!isCancelled)
// {
// channel.Writer.TryWrite(CancelType.Manual);
// _channels[signal] = (channel, true, false); // 标记为已取消
// _channels.TryRemove(signal, out _); // 从字典中移除信号
// return true;
// }
// }
// }
// return false;
// }
// /// <summary>
// /// 启用丢弃模式,所有后续获取的信号将直接返回丢弃类型
// /// </summary>
// /// <param name="signal">信号标识符</param>
// public void EnableDiscardMode(string signal,bool state = true)
// {
// lock (_lock)
// {
// if (_channels.TryGetValue(signal, out var channelInfo))
// {
// var (channel, isCancelled, _) = channelInfo;
// _channels[signal] = (channel, isCancelled, state); // 标记为丢弃模式
// }
// }
// }
// /// <summary>
// /// 取消所有任务
// /// </summary>
// public void CancelAllTasks()
// {
// foreach (var (channel, _, _) in _channels.Values)
// {
// try
// {
// channel.Writer.Complete();
// }
// catch
// {
// // 忽略完成时的异常
// }
// }
// _channels.Clear();
// }
// /// <summary>
// /// 获取或创建指定信号的 Channel 通道
// /// </summary>
// private (Channel<CancelType>, bool, bool) GetOrCreateChannel(string signal)
// {
// lock (_lock)
// {
// return _channels.GetOrAdd(signal, _ => (Channel.CreateUnbounded<CancelType>(), false, false));
// }
// }
// }
//}
#endregion

View File

@@ -10,41 +10,15 @@ using System.Threading.Channels;
using System.Threading.Tasks;
using System.Transactions;
namespace Serein.Library
namespace Serein.Library.Utils
{
/// <summary>
/// 触发类型
/// </summary>
public enum TriggerDescription
{
/// <summary>
/// 外部触发
/// </summary>
External,
/// <summary>
/// 超时触发
/// </summary>
Overtime,
/// <summary>
/// 触发了,但类型不一致
/// </summary>
TypeInconsistency
}
public class TriggerResult<TResult>
{
public TriggerDescription Type { get; set; }
public TResult Value { get; set; }
}
/// <summary>
/// 信号触发器类,带有消息广播功能。
/// 使用枚举作为标记,创建
/// </summary>
public class TaskFlowTrigger<TSignal> : IFlowTrigger<TSignal> where TSignal : struct, Enum
public class ValueTaskFlowTrigger<TSignal>
{
// 使用并发字典管理每个信号对应的广播列表
private readonly ConcurrentDictionary<TSignal, Subject<TriggerResult<object>>> _subscribers = new ConcurrentDictionary<TSignal, Subject<TriggerResult<object>>>();
@@ -73,7 +47,7 @@ namespace Serein.Library
}
/// <summary>
/// 等待触发器并指定超时的时间
/// </summary>
@@ -81,7 +55,7 @@ namespace Serein.Library
/// <param name="signal">等待信号</param>
/// <param name="outTime">超时时间</param>
/// <returns></returns>
public async Task<TriggerResult<TResult>> WaitTriggerWithTimeoutAsync<TResult>(TSignal signal, TimeSpan outTime)
public async ValueTask<TriggerResult<TResult>> WaitTriggerWithTimeoutAsync<TResult>(TSignal signal, TimeSpan outTime)
{
var subject = GetOrCreateSubject(signal);
var cts = new CancellationTokenSource();
@@ -121,13 +95,14 @@ namespace Serein.Library
/// <typeparam name="TResult"></typeparam>
/// <param name="signal"></param>
/// <returns></returns>
public async Task<TriggerResult<TResult>> WaitTriggerAsync<TResult>(TSignal signal)
public async ValueTask<TriggerResult<TResult>> WaitTriggerAsync<TResult>(TSignal signal)
{
var taskCompletionSource = new TaskCompletionSource<TriggerResult<object>>();
var subscription = Subscribe<TResult>(signal, taskCompletionSource.SetResult);
var result = await taskCompletionSource.Task;
subscription.Dispose(); // 取消订阅
if(result.Value is TResult data)
if (result.Value is TResult data)
{
return new TriggerResult<TResult>()
{
@@ -184,23 +159,5 @@ namespace Serein.Library
/// <summary>
/// 观察者类,用于包装 Action
/// </summary>
public class Observer<T> : IObserver<T>
{
private readonly Action<T> _onNext;
public Observer(Action<T> onNext)
{
_onNext = onNext;
}
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(T value)
{
_onNext?.Invoke(value);
}
}
}

View File

@@ -1,6 +1,4 @@

using Serein.Library.Api;
using Serein.Library.Api;
using System;
using System.Collections.Concurrent;
using System.Threading;
@@ -13,7 +11,7 @@ namespace Serein.Library.Utils
public class ChannelFlowTrigger<TSignal> : IFlowTrigger<TSignal>
public class ChannelFlowTrigger<TSignal> : IFlowTrigger<TSignal>
{
// 使用并发字典管理每个枚举信号对应的 Channel
private readonly ConcurrentDictionary<TSignal, Channel<TriggerResult<object>>> _channels = new ConcurrentDictionary<TSignal, Channel<TriggerResult<object>>>();

View File

@@ -0,0 +1,160 @@
using Microsoft.Extensions.ObjectPool;
using Newtonsoft.Json.Linq;
using Serein.Library.Api;
using Serein.Library.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Transactions;
namespace Serein.Library.Utils
{
/// <summary>
/// 信号触发器类,带有消息广播功能。
/// 使用枚举作为标记,创建
/// </summary>
public class TaskFlowTrigger<TSignal> : IFlowTrigger<TSignal>
{
// 使用并发字典管理每个信号对应的广播列表
private readonly ConcurrentDictionary<TSignal, Subject<TriggerResult<object>>> _subscribers = new ConcurrentDictionary<TSignal, Subject<TriggerResult<object>>>();
private readonly TriggerResultPool _triggerResultPool = new TriggerResultPool();
/// <summary>
/// 获取或创建指定信号的 Subject消息广播者
/// </summary>
/// <param name="signal">枚举信号标识符</param>
/// <returns>对应的 Subject</returns>
private Subject<TriggerResult<object>> GetOrCreateSubject(TSignal signal)
{
return _subscribers.GetOrAdd(signal, _ => new Subject<TriggerResult<object>>());
}
/// <summary>
/// 订阅指定信号的消息
/// </summary>
/// <param name="signal">枚举信号标识符</param>
/// <param name="action">订阅者</param>
/// <returns>取消订阅的句柄</returns>
private IDisposable Subscribe<TResult>(TSignal signal, Action<TriggerResult<object>> action)
{
IObserver<TriggerResult<object>> observer = new Observer<TriggerResult<object>>(action);
var subject = GetOrCreateSubject(signal);
return subject.Subscribe(observer); // 返回取消订阅的句柄
}
/// <summary>
/// 等待触发器并指定超时的时间
/// </summary>
/// <typeparam name="TResult">返回值类型</typeparam>
/// <param name="signal">等待信号</param>
/// <param name="outTime">超时时间</param>
/// <returns></returns>
public async Task<TriggerResult<TResult>> WaitTriggerWithTimeoutAsync<TResult>(TSignal signal, TimeSpan outTime)
{
var subject = GetOrCreateSubject(signal);
var cts = new CancellationTokenSource();
// 超时任务:延迟后触发超时信号
var timeoutTask = Task.Delay(outTime, cts.Token).ContinueWith(t =>
{
if (!cts.Token.IsCancellationRequested)
{
var outResult = _triggerResultPool.Get();
outResult.Type = TriggerDescription.Overtime;
subject.OnNext(outResult);
subject.OnCompleted();
}
}, cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
var result = await WaitTriggerAsync<TResult>(signal); // 获取触发的结果
cts.Cancel(); // 取消超时任务
await timeoutTask; // 确保超时任务完成
cts.Dispose();
return result;
}
/// <summary>
/// 等待触发
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="signal"></param>
/// <returns></returns>
public async Task<TriggerResult<TResult>> WaitTriggerAsync<TResult>(TSignal signal)
{
var taskCompletionSource = new TaskCompletionSource<TriggerResult<object>>();
var subscription = Subscribe<TResult>(signal, taskCompletionSource.SetResult);
var result = await taskCompletionSource.Task;
subscription.Dispose(); // 取消订阅
var result2 = result.Value is TResult data
? new TriggerResult<TResult> { Value = data, Type = TriggerDescription.External }
: new TriggerResult<TResult> { Type = TriggerDescription.TypeInconsistency };
_triggerResultPool.Return(result); // 将结果归还池中
return result2;
}
/// <summary>
/// 手动触发信号,并广播给所有订阅者
/// </summary>
/// <typeparam name="TResult">触发类型</typeparam>
/// <param name="signal">枚举信号标识符</param>
/// <param name="value">传递的数据</param>
/// <returns>是否成功触发</returns>
public Task<bool> InvokeTriggerAsync<TResult>(TSignal signal, TResult value)
{
if (_subscribers.TryGetValue(signal, out var subject))
{
var result = _triggerResultPool.Get();
result.Type = TriggerDescription.External;
result.Value = value;
subject.OnNext(result); // 广播给所有订阅者
subject.OnCompleted(); // 通知订阅结束
return Task.FromResult(true);
}
return Task.FromResult(false);
}
/// <summary>
/// 取消所有任务
/// </summary>
public void CancelAllTrigger()
{
foreach (var subject in _subscribers.Values)
{
subject.OnCompleted(); // 通知所有订阅者结束
}
_subscribers.Clear();
}
}
/// <summary>
/// 观察者类,用于包装 Action
/// </summary>
public class Observer<T> : IObserver<T>
{
private readonly Action<T> _onNext;
public Observer(Action<T> onNext)
{
_onNext = onNext;
}
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(T value)
{
_onNext?.Invoke(value);
}
}
}

View File

@@ -0,0 +1,112 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.Library.Utils
{
public class TriggerResult<TResult>
{
public TriggerDescription Type { get; set; }
public TResult Value { get; set; }
}
/// <summary>
/// 对象池队列
/// </summary>
public class ConcurrentExpandingObjectPool<T> where T : class, new()
{
private readonly ConcurrentQueue<T> _pool; // 存储池中对象的队列
public ConcurrentExpandingObjectPool(int initialCapacity)
{
// 初始化对象池,初始容量为 initialCapacity
_pool = new ConcurrentQueue<T>();
// 填充初始对象
for (int i = 0; i < initialCapacity; i++)
{
_pool.Enqueue(new T());
}
}
/// <summary>
/// 获取一个对象,如果池中没有对象,则动态创建新的对象
/// </summary>
/// <returns>池中的一个对象</returns>
public T Get()
{
// 尝试从池中获取一个对象
if (!_pool.TryDequeue(out var item))
{
// 如果池为空,则创建一个新的对象
item = new T();
}
return item;
}
/// <summary>
/// 将一个对象归还到池中
/// </summary>
/// <param name="item">需要归还的对象</param>
public void Return(T item)
{
// 将对象归还到池中
_pool.Enqueue(item);
}
/// <summary>
/// 获取当前池中的对象数
/// </summary>
public int CurrentSize => _pool.Count;
/// <summary>
/// 清空池中的所有对象
/// </summary>
public void Clear()
{
while (_pool.TryDequeue(out _)) { } // 清空队列
}
}
/// <summary>
/// 使用 ObjectPool 来复用 TriggerResult 对象
/// </summary>
// 示例 TriggerResult 对象池
public class TriggerResultPool
{
private readonly ConcurrentExpandingObjectPool<TriggerResult<object>> _objectPool;
public TriggerResultPool(int defaultCapacity = 30)
{
_objectPool = new ConcurrentExpandingObjectPool<TriggerResult<object>>(defaultCapacity);
}
public TriggerResult<object> Get() => _objectPool.Get();
public void Return(TriggerResult<object> result) => _objectPool.Return(result);
}
/// <summary>
/// 触发类型
/// </summary>
public enum TriggerDescription
{
/// <summary>
/// 外部触发
/// </summary>
External,
/// <summary>
/// 超时触发
/// </summary>
Overtime,
/// <summary>
/// 触发了,但类型不一致
/// </summary>
TypeInconsistency
}
}