2024-08-06 16:09:46 +08:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
|
using Serein.NodeFlow;
|
2024-09-09 16:42:01 +08:00
|
|
|
|
using Serein.NodeFlow.Model;
|
2024-08-06 16:09:46 +08:00
|
|
|
|
|
|
|
|
|
|
namespace Serein.NodeFlow.Tool
|
|
|
|
|
|
{
|
|
|
|
|
|
public class TcsSignalException : Exception
|
|
|
|
|
|
{
|
2024-09-09 16:42:01 +08:00
|
|
|
|
public FlowStateType FsState { get; set; }
|
2024-08-06 16:09:46 +08:00
|
|
|
|
public TcsSignalException(string? message) : base(message)
|
|
|
|
|
|
{
|
2024-09-09 16:42:01 +08:00
|
|
|
|
FsState = FlowStateType.Error;
|
2024-08-06 16:09:46 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public class TcsSignal<TSignal> where TSignal : struct, Enum
|
|
|
|
|
|
{
|
2024-09-09 21:06:47 +08:00
|
|
|
|
//public ConcurrentDictionary<TSignal, Queue<TaskCompletionSource<object>>> TcsEvent { get; } = new();
|
|
|
|
|
|
public ConcurrentDictionary<TSignal, TaskCompletionSource<object>> TcsEvent { get; } = new();
|
|
|
|
|
|
public ConcurrentDictionary<TSignal, object> TcsValue { get; } = new();
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 触发信号
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
|
|
|
/// <param name="signal">信号</param>
|
|
|
|
|
|
/// <param name="value">传递的参数</param>
|
|
|
|
|
|
/// <returns>是否成功触发</returns>
|
|
|
|
|
|
public bool TriggerSignal<T>(TSignal signal, T value)
|
2024-08-06 16:09:46 +08:00
|
|
|
|
{
|
2024-09-09 21:06:47 +08:00
|
|
|
|
if (TcsEvent.TryRemove(signal, out var waitTcs))
|
2024-08-06 16:09:46 +08:00
|
|
|
|
{
|
2024-09-09 21:06:47 +08:00
|
|
|
|
waitTcs.SetResult(value);
|
2024-08-06 16:09:46 +08:00
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public TaskCompletionSource<object> CreateTcs(TSignal signal)
|
|
|
|
|
|
{
|
2024-09-09 21:06:47 +08:00
|
|
|
|
var tcs = TcsEvent.GetOrAdd(signal,_ = new TaskCompletionSource<object>());
|
2024-08-06 16:09:46 +08:00
|
|
|
|
return tcs;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public void CancelTask()
|
|
|
|
|
|
{
|
|
|
|
|
|
lock (TcsEvent)
|
|
|
|
|
|
{
|
2024-09-09 21:06:47 +08:00
|
|
|
|
foreach (var tcs in TcsEvent.Values)
|
2024-08-06 16:09:46 +08:00
|
|
|
|
{
|
2024-09-09 21:06:47 +08:00
|
|
|
|
tcs.SetException(new TcsSignalException("任务取消"));
|
2024-08-06 16:09:46 +08:00
|
|
|
|
}
|
|
|
|
|
|
TcsEvent.Clear();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|