App.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using ivf_tl_Services;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Threading;
  13. namespace ivf_tl_Operate
  14. {
  15. /// <summary>
  16. /// Interaction logic for App.xaml
  17. /// </summary>
  18. public partial class App : Application
  19. {
  20. private static Mutex instance;
  21. // 当前生效的语言资源字典(运行时由 ChangeLanguage 维护)。用于按引用精确移除旧语言字典,
  22. // 避免历史 bug:盲删最后一个 MergedDictionary 误删 AdaptiveStyles(TouchMinSize)。
  23. private ResourceDictionary _currentLangRd;
  24. public App()
  25. {
  26. Log4netHelper.WriteLog("App构造函数运行");
  27. //首先注册开始和退出事件
  28. this.Startup += new StartupEventHandler(App_Startup);
  29. this.Exit += new ExitEventHandler(App_Exit);
  30. }
  31. protected override void OnStartup(StartupEventArgs e)
  32. {
  33. bool isNotRunning; //互斥体判断
  34. instance = new Mutex(true, "ivf_tl_Operate", out isNotRunning); //同步基元变量
  35. if (!isNotRunning) // 如果不是未运行状态
  36. {
  37. MessageBox.Show("程序已启动 ");
  38. App.Current.Shutdown();
  39. return;
  40. }
  41. base.OnStartup(e);
  42. AppContext.SetSwitch("Switch.System.Windows.Input.Stylus.EnablePointerSupport", true);
  43. }
  44. private void App_Exit(object sender, ExitEventArgs e)
  45. {
  46. }
  47. private void App_Startup(object sender, StartupEventArgs e)
  48. {
  49. //UI线程未捕获异常处理事件
  50. this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
  51. //Task线程内未捕获异常处理事件
  52. TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  53. //非UI线程未捕获异常处理事件
  54. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  55. // M5-02-5:启动时一次性凭据迁移(明文 passWord/engineerPwd → 密文,幂等)。须先于读取凭据。
  56. ivf_tl_Operate.Helpers.AppConfigHelper.MigratePlaintextCredentials();
  57. // M8-P3b:操作日志组件启动初始化(一次)。project=operate,Kafka 从 App.config kfkaIP+kfkaPort。
  58. InitOperationLog();
  59. ChangeLanguage(ConfigurationManager.AppSettings["Language"].ToString());
  60. }
  61. /// <summary>
  62. /// M8-P3b:初始化操作日志组件。Kafka 地址取 App.config 的 kfkaIP/kfkaPort;topic=tl-oplog。
  63. /// 全 try 兜底:日志初始化失败绝不影响业务启动。
  64. /// </summary>
  65. private void InitOperationLog()
  66. {
  67. try
  68. {
  69. string kafkaIp = ConfigurationManager.AppSettings["kfkaIP"]?.ToString() ?? "127.0.0.1";
  70. string kafkaPort = ConfigurationManager.AppSettings["kfkaPort"]?.ToString() ?? "9092";
  71. Aivfo.OperationLog.OperationLogger.Init(o =>
  72. {
  73. o.Project = "operate";
  74. o.KafkaBootstrapServers = $"{kafkaIp}:{kafkaPort}";
  75. o.Topic = "tl-oplog";
  76. });
  77. Log4netHelper.WriteLog($"[M8-P3b]操作日志组件已初始化 kafka={kafkaIp}:{kafkaPort} topic=tl-oplog");
  78. }
  79. catch (Exception ex)
  80. {
  81. // 兜底:组件本身也兜底,这里再保一层,绝不因日志初始化影响启动。
  82. try { Log4netHelper.WriteLog($"[M8-P3b]操作日志组件初始化失败(已忽略):{ex.Message}"); } catch { }
  83. }
  84. }
  85. /// <summary>
  86. /// 非UI线程未捕获异常处理事件
  87. /// </summary>
  88. /// <param name="sender"></param>
  89. /// <param name="e"></param>
  90. /// <exception cref="NotImplementedException"></exception>
  91. private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  92. {
  93. try
  94. {
  95. if (e.IsTerminating)
  96. {
  97. Log4netHelper.WriteLog($"非UI线程发生致命错误,程序即将终止");
  98. }
  99. if (e.ExceptionObject is Exception ex)
  100. {
  101. if (ex.InnerException != null)
  102. {
  103. Log4netHelper.WriteLog($"非UI线程异常详细:{ex.InnerException.Message}{ex.InnerException.StackTrace}");
  104. }
  105. Log4netHelper.WriteLog($"非UI线程异常:{ex.Message}{ex.StackTrace}");
  106. }
  107. else
  108. {
  109. Log4netHelper.WriteLog($"非UI线程异常:异常对象类型不是Exception");
  110. }
  111. }
  112. catch (Exception exx)
  113. {
  114. if (exx.InnerException != null)
  115. {
  116. Log4netHelper.WriteLog($"捕获非UI线程异常时发生异常详细:{exx.InnerException.Message}{exx.InnerException.StackTrace}");
  117. }
  118. Log4netHelper.WriteLog($"捕获非UI线程异常时发生异常:{exx.Message}{exx.StackTrace}");
  119. }
  120. }
  121. /// <summary>
  122. /// Task线程内未捕获异常处理事件
  123. /// </summary>
  124. /// <param name="sender"></param>
  125. /// <param name="e"></param>
  126. /// <exception cref="NotImplementedException"></exception>
  127. private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
  128. {
  129. try
  130. {
  131. if (e.Exception.InnerException != null)
  132. {
  133. Log4netHelper.WriteLog($"Task线程异常详细:{e.Exception.InnerException.Message}{e.Exception.InnerException.StackTrace}");
  134. }
  135. Log4netHelper.WriteLog($"Task线程异常:{e.Exception.Message}{e.Exception.StackTrace}");
  136. e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
  137. }
  138. catch (Exception ex)
  139. {
  140. if (ex.InnerException != null)
  141. {
  142. Log4netHelper.WriteLog($"捕获Task线程异常时发生异常详细:{ex.InnerException.Message}{ex.InnerException.StackTrace}");
  143. }
  144. Log4netHelper.WriteLog($"捕获Task线程异常时发生异常:{ex.Message}{ex.StackTrace}");
  145. }
  146. finally
  147. {
  148. e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
  149. }
  150. }
  151. /// <summary>
  152. /// UI线程未捕获异常处理事件
  153. /// </summary>
  154. /// <param name="sender"></param>
  155. /// <param name="e"></param>
  156. /// <exception cref="NotImplementedException"></exception>
  157. // === 日志洪流抑制(防 8GB 复发)===
  158. // WPF 布局类异常被下面 e.Handled=true 吞掉后,WPF 会逐帧重新测量→同一异常每帧重抛。
  159. // 无节流时同一条异常每秒上千次、每条带完整堆栈(~4.7KB),曾致单日日志涨到 8GB。
  160. // 此处按异常签名节流:同签名 10s 内只放行一条,下次放行时补记期间被抑制的条数。
  161. private static readonly object _logThrottleLock = new object();
  162. private static readonly Dictionary<string, long[]> _logThrottle = new Dictionary<string, long[]>(); // signature -> [lastTicks, suppressedCount]
  163. private static readonly long _logThrottleWindowTicks = TimeSpan.FromSeconds(10).Ticks;
  164. /// <summary>
  165. /// 节流判定:同 <paramref name="signature"/> 在窗口期(10s)内只放行一次。
  166. /// 返回 true=应记录(<paramref name="suppressNote"/> 含上一窗口被抑制的条数提示);false=抑制本条。线程安全。
  167. /// </summary>
  168. private static bool ShouldLogThrottled(string signature, out string suppressNote)
  169. {
  170. suppressNote = string.Empty;
  171. long now = DateTime.Now.Ticks;
  172. lock (_logThrottleLock)
  173. {
  174. if (_logThrottle.TryGetValue(signature, out long[] st))
  175. {
  176. if (now - st[0] < _logThrottleWindowTicks)
  177. {
  178. st[1]++; // 仍在窗口内:累计被抑制条数,不记录
  179. return false;
  180. }
  181. if (st[1] > 0) suppressNote = $"(前 10s 抑制 {st[1]} 条相同异常)";
  182. st[0] = now;
  183. st[1] = 0;
  184. return true;
  185. }
  186. _logThrottle[signature] = new long[] { now, 0 };
  187. return true;
  188. }
  189. }
  190. private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
  191. {
  192. try
  193. {
  194. // 按异常消息节流(布局类异常被吞后会逐帧重抛,见上方说明)。
  195. if (ShouldLogThrottled("UI:" + (e.Exception?.Message ?? "null"), out string note))
  196. {
  197. if (e.Exception.InnerException != null)
  198. {
  199. Log4netHelper.WriteLog($"UI线程异常详细:{e.Exception.InnerException.Message}{e.Exception.InnerException.StackTrace}");
  200. }
  201. Log4netHelper.WriteLog($"UI线程异常{note}:{e.Exception.Message}{e.Exception.StackTrace}");
  202. }
  203. //把 Handled 属性设为true,表示此异常已处理,程序可以继续运行,不会强制退出
  204. }
  205. catch (Exception ex)
  206. {
  207. //此时程序出现严重异常,将强制结束退出
  208. if (ex.InnerException != null)
  209. {
  210. Log4netHelper.WriteLog($"捕获UI线程异常时发生异常详细:{ex.InnerException.Message}{ex.InnerException.StackTrace}");
  211. }
  212. Log4netHelper.WriteLog($"捕获UI线程异常时发生异常:{ex.Message}{ex.StackTrace}");
  213. }
  214. finally
  215. {
  216. e.Handled = true;
  217. }
  218. }
  219. public void ChangeLanguage(string languageName)
  220. {
  221. try
  222. {
  223. ResourceDictionary langRd = null;
  224. #if DEBUG
  225. string xamlFilePath = @"C:\PersonalSpace\work\1 VisualWorkSpace\SurfaceLan\" + languageName;
  226. #else
  227. string xamlFilePath = $"{System.AppDomain.CurrentDomain.BaseDirectory}Resources\\Language\\{languageName}";
  228. #endif
  229. if (!File.Exists(xamlFilePath))
  230. {
  231. Log4netHelper.WriteLog($"切换语言失败,配置文件不存在:{xamlFilePath}");
  232. return;
  233. }
  234. using (var stream = new FileStream(xamlFilePath, FileMode.Open))
  235. {
  236. langRd = System.Windows.Markup.XamlReader.Load(stream) as ResourceDictionary;
  237. }
  238. if (langRd != null)
  239. {
  240. var mds = Application.Current.Resources.MergedDictionaries;
  241. // 【8GB 洪流根因修复】原逻辑 RemoveAt(Count-1) 盲删"最后一个"合并字典。
  242. // 但 App.xaml 里最后一个是 AdaptiveStyles.xaml(全局 TouchMinSize 所在,M4-01-4 加在语言字典之后),
  243. // 故启动时本方法实删的是 AdaptiveStyles 而非旧语言字典 → 全局 TouchMinSize 丢失 →
  244. // SoftKeyboard 按键隐式样式 MinHeight={StaticResource TouchMinSize} 解析成 UnsetValue → 每帧抛 → 单日 8GB。
  245. // 改为:按引用移除"上一次语言字典";首次按 Source 含 /Language/ 匹配移除 App.xaml 预置语言字典,绝不碰 AdaptiveStyles。
  246. if (_currentLangRd != null)
  247. {
  248. mds.Remove(_currentLangRd);
  249. }
  250. else
  251. {
  252. for (int i = mds.Count - 1; i >= 0; i--)
  253. {
  254. string src = mds[i].Source?.OriginalString ?? string.Empty;
  255. if (src.IndexOf("/Language/", StringComparison.OrdinalIgnoreCase) >= 0)
  256. {
  257. mds.RemoveAt(i);
  258. break;
  259. }
  260. }
  261. }
  262. mds.Add(langRd);
  263. _currentLangRd = langRd;
  264. }
  265. else
  266. {
  267. Log4netHelper.WriteLog($"切换语言失败,文件转ResourceDictionary失败;{xamlFilePath}");
  268. }
  269. }
  270. catch (Exception ex)
  271. {
  272. Log4netHelper.WriteLog($"切换语言异常,{JsonConvert.SerializeObject(ex)}");
  273. return;
  274. }
  275. }
  276. }
  277. }