using System; using System.Collections.Generic; using System.IO; using System.IO.Pipes; using System.Text; using System.Threading; namespace YuncangTrace.LocalService.Services; /// /// 单实例 + 参数转发(命名管道) /// /// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。 /// 这时第二个实例**不应该**去抢 17300 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例, /// 由它把窗口激活并查询那个运单号。 /// public sealed class SingleInstance : IDisposable { private readonly Mutex _mutex; private readonly string _pipeName; private readonly Action _onArgs; private readonly CancellationTokenSource _cts = new(); private readonly bool _ownsMutex; /// 本次是否是第一个实例(不是的话调用 后就可以退出了) public bool IsFirstInstance { get; } public SingleInstance(string name, Action onArgs) { _onArgs = onArgs; _pipeName = $"{name}.pipe"; // 全局命名互斥体:跨会话也能认出来(同一个用户下就够了,用 Local\ 前缀) _mutex = new Mutex(initiallyOwned: true, $@"Local\{name}.mutex", out var createdNew); _ownsMutex = createdNew; IsFirstInstance = createdNew; } /// 第一个实例调用:开一个后台线程等第二个实例送参数过来 public void StartListening() { var thread = new Thread(ListenLoop) { IsBackground = true, Name = "single-instance-pipe", }; thread.Start(); } /// /// 第二个实例调用:把命令行参数送给已运行的实例。 /// 返回 false = 送不出去(常见原因:第一个实例是**管理员权限**,中完整性的第二个实例写不进它的管道)。 /// public bool SendArgs(string[] args) { if (args.Length == 0) return true; try { using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out); client.Connect(1500); using var writer = new StreamWriter(client, new UTF8Encoding(false)) { AutoFlush = true }; foreach (var arg in args) writer.WriteLine(arg); return true; } catch (Exception ex) { // 以前这里静默吞掉 → 用户看到的就是“唤起没反应”;现在返回给调用方提示 AppLog.Write($"[single] 参数转发失败(第一个实例可能是管理员权限):{ex.Message}"); return false; } } private void ListenLoop() { while (!_cts.IsCancellationRequested) { try { using var server = new NamedPipeServerStream( _pipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.None); server.WaitForConnection(); var args = new List(); using (var reader = new StreamReader(server, new UTF8Encoding(false))) { string? line; while ((line = reader.ReadLine()) is not null) { if (line.Length > 0) args.Add(line); } } if (args.Count > 0) _onArgs(args.ToArray()); } catch (Exception) { if (_cts.IsCancellationRequested) return; Thread.Sleep(200); } } } public void Dispose() { _cts.Cancel(); if (_ownsMutex) { try { _mutex.ReleaseMutex(); } catch (ApplicationException) { // 不持有互斥体(理论上不会发生) } } _mutex.Dispose(); _cts.Dispose(); } }