packServer/desktop/Services/SingleInstance.cs
liufumingren fe8c0d62a1 chore(ports): 本机服务与边缘代理端口整体迁出 173xx
- 桌面端本机 HTTP/WS:17300/17301 → 16000/16001(前端、浏览器扩展、文档同步)
- 后台服务局域网:UDP 17310/TCP 17311 → UDP 16100/TCP 16101(16010 被向日葵占用,统一避开 160xx)
- 防火墙规则随端口更新,安装/升级时清理旧 17xxx 规则,避免继续占用别人的端口
- 桌面端版本升到 1.0.162

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-18 15:51:41 +08:00

133 lines
4.5 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 单实例 + 参数转发(命名管道)
///
/// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。
/// 这时第二个实例**不应该**去抢 16000 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
/// 由它把窗口激活并查询那个运单号。
/// </summary>
public sealed class SingleInstance : IDisposable
{
/// <summary>第二个实例「只想把界面叫出来」(双击快捷方式,没带任何参数)</summary>
public const string ShowCommand = "--show";
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly Action<string[]> _onArgs;
private readonly CancellationTokenSource _cts = new();
private readonly bool _ownsMutex;
/// <summary>本次是否是第一个实例(不是的话调用 <see cref="SendArgs"/> 后就可以退出了)</summary>
public bool IsFirstInstance { get; }
public SingleInstance(string name, Action<string[]> onArgs)
{
_onArgs = onArgs;
_pipeName = $"{name}.pipe";
// 全局命名互斥体:跨会话也能认出来(同一个用户下就够了,用 Local\ 前缀)
_mutex = new Mutex(initiallyOwned: true, $@"Local\{name}.mutex", out var createdNew);
_ownsMutex = createdNew;
IsFirstInstance = createdNew;
}
/// <summary>第一个实例调用:开一个后台线程等第二个实例送参数过来</summary>
public void StartListening()
{
var thread = new Thread(ListenLoop)
{
IsBackground = true,
Name = "single-instance-pipe",
};
thread.Start();
}
/// <summary>
/// 第二个实例调用:把命令行参数送给已运行的实例。
/// 返回 false = 送不出去(常见原因:第一个实例是**管理员权限**,中完整性的第二个实例写不进它的管道)。
///
/// ⚠️ 没有参数(双击快捷方式)也要送一条 <see cref="ShowCommand"/>:以前这里直接 return true 什么都不发,
/// 第二个实例紧接着就退出 → 用户看到的就是「点图标没反应,主界面打不开」。
/// </summary>
public bool SendArgs(string[] args)
{
var payload = args is { Length: > 0 } ? args : new[] { ShowCommand };
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 payload) 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<string>();
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();
}
}