using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace GZ.Projects.AuxAllWCS { public partial class AutoThread { private static AutoThread _instance; // 私有构造函数防止外部实例化 private AutoThread() { } public static AutoThread Instance { get { if (_instance == null) { _instance = new AutoThread(); } return _instance; } } // 线程安全的委托缓存 private static readonly ConcurrentDictionary _methodCache = new ConcurrentDictionary(); // 方法执行器 public static object InvokeMethod(object instance, string methodName, params object[] args) { var cacheKey = $"{instance.GetType().FullName}_{methodName}"; if (!_methodCache.TryGetValue(cacheKey, out var methodDelegate)) { // 获取方法信息 var methodInfo = instance.GetType().GetMethod( methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo == null) throw new MissingMethodException($"Method {methodName} not found"); // 创建委托并缓存 methodDelegate = Delegate.CreateDelegate( GetDelegateType(methodInfo), instance, methodInfo); _methodCache.TryAdd(cacheKey, methodDelegate); } // 执行委托 return methodDelegate.DynamicInvoke(args); } // 根据方法签名生成对应的委托类型 private static Type GetDelegateType(MethodInfo methodInfo) { var parameterTypes = methodInfo.GetParameters() .Select(p => p.ParameterType) .ToList(); if (methodInfo.ReturnType == typeof(void)) { return System.Linq.Expressions.Expression.GetActionType(parameterTypes.ToArray()); } else { parameterTypes.Add(methodInfo.ReturnType); return System.Linq.Expressions.Expression.GetFuncType(parameterTypes.ToArray()); } } public void ThreadSettingInit(Tag tag, Action action) { Console.WriteLine("初始化配置 线程 run " + tag.Global.SettingsOver); if (tag.Global.SettingsOver == 0) { action?.Invoke(); tag.Global.SettingsOver = 1; } else if (Settings.deviceInfos.Count == 0) { tag.Global.SettingsOver = 0; } } } }