using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.Concurrent; namespace BPASmartClient.Helper { public class ActionManage { private volatile static ActionManage _Instance; public static ActionManage GetInstance => _Instance ?? (_Instance = new ActionManage()); private ActionManage() { } //private static ConcurrentDictionary actions = new ConcurrentDictionary(); private static ConcurrentDictionary actions = new ConcurrentDictionary(); static readonly object SendLock = new object(); static readonly object SendParLock = new object(); static readonly object RegisterLock = new object(); /// /// 注销委托 /// /// public void CancelRegister(string key) { if (actions.ContainsKey(key)) actions.TryRemove(key, out Delegation t); } /// /// 执行注册过的委托 /// /// 注册委托的key /// 委托参数 /// 委托回调 public void Send(string key, object par, Action Callback = null) { lock (SendLock) if (actions.ContainsKey(key)) actions[key].ActionPar.Invoke(par, Callback); } /// /// 执行注册过的委托 /// /// 注册委托的key /// 委托参数 /// 委托回调 public void Send(string key, object[] par, Action Callback = null) { lock (SendLock) if (actions.ContainsKey(key)) actions[key].ActionPars.Invokes(par, Callback); } /// /// 执行注册过的委托 /// /// 注册委托的key /// 委托回调 public void Send(string key, Action Callback = null) { lock (SendLock) if (actions.ContainsKey(key)) actions[key].ActionBus?.Invoke(Callback); } public object SendResult(string key, object par = null) { lock (SendLock) if (actions.ContainsKey(key)) if (par == null) { //if (actions[key].FuncObj != null) return actions[key].FuncObj?.Invoke(); } else { //if (actions[key].FuncPar != null) return actions[key].FuncPar?.Invoke(par); } return default; } public void Register(T action, string key) { lock (RegisterLock) { if (action != null) { if (!actions.ContainsKey(key)) { if (action is Action actionBus) actions.TryAdd(key, new Delegation() { ActionBus = actionBus }); if (action is Action actionObj) actions.TryAdd(key, new Delegation() { ActionPar = actionObj }); if (action is Action actionObjs) actions.TryAdd(key, new Delegation() { ActionPars = actionObjs }); if (action is Func funcObj) actions.TryAdd(key, new Delegation() { FuncObj = funcObj }); if (action is Func puncPar) actions.TryAdd(key, new Delegation() { FuncPar = puncPar }); } } } } } internal class Delegation { /// /// 带参数的委托 /// public Action ActionPar { get; set; } /// /// 带参数的委托 /// public Action ActionPars { get; set; } /// /// 无参数的委托 /// public Action ActionBus { get; set; } /// /// 有返回值的委托 /// public Func FuncObj { get; set; } /// /// 有返回值,有参数的委托 /// public Func FuncPar { get; set; } } }