using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using NewLife.Log;
namespace NewLife.XCoder.Services;
/// <summary>单实例:保证只跑一个进程,并让重复启动的实例唤醒已有窗口</summary>
/// <remarks>
/// 用命名互斥体判断是否首实例;首实例再监听一个命名管道,
/// 后启动的实例连上管道发一条激活消息就退出,用户看到的是「窗口被拎到最前」而不是「点了没反应」。
/// 命名管道在 Windows 与 Unix 上均可用,因此三平台同一套逻辑。
/// </remarks>
public sealed class SingleInstanceService : IDisposable
{
private readonly Mutex _mutex;
private readonly CancellationTokenSource _cts = new();
private Task? _server;
/// <summary>管道名称</summary>
public String PipeName { get; }
/// <summary>是否首实例(首实例才启动界面)</summary>
public Boolean IsFirst { get; }
/// <summary>收到「请激活窗口」请求时触发(后台线程)</summary>
public event Action? ActivateRequested;
/// <summary>实例化并抢占单实例锁</summary>
/// <param name="mutexName">互斥体名称</param>
/// <param name="pipeName">管道名称</param>
public SingleInstanceService(String mutexName = "NewLife.XCoder.SingleInstance", String pipeName = "NewLife.XCoder.Activate")
{
PipeName = pipeName;
try
{
// 不申请所有权(initiallyOwned:false),只用「名字是否已存在」判断首实例,
// 否则第二实例会在构造时阻塞等待,看起来像卡死。
_mutex = new Mutex(false, mutexName, out var createdNew);
IsFirst = createdNew;
}
catch (Exception ex)
{
// 互斥体不可用时退回「允许多开」,不影响使用
XTrace.WriteException(ex);
_mutex = new Mutex();
IsFirst = true;
}
}
/// <summary>首实例启动管道监听</summary>
public void StartServer()
{
if (!IsFirst || _server != null) return;
var token = _cts.Token;
_server = Task.Run(() => ServerLoop(token));
}
private async Task ServerLoop(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
await server.WaitForConnectionAsync(token).ConfigureAwait(false);
var buffer = new Byte[16];
var count = await server.ReadAsync(buffer, token).ConfigureAwait(false);
if (count > 0) ActivateRequested?.Invoke();
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
// 管道异常不致命:稍后重建即可
XTrace.WriteException(ex);
try { await Task.Delay(500, token).ConfigureAwait(false); } catch { break; }
}
}
}
/// <summary>通知已有实例激活窗口</summary>
/// <param name="timeoutMilliseconds">连接超时</param>
/// <returns>是否送达</returns>
public Boolean NotifyExisting(Int32 timeoutMilliseconds = 1500)
{
try
{
using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out);
client.Connect(timeoutMilliseconds);
var buffer = "activate"u8.ToArray();
client.Write(buffer, 0, buffer.Length);
client.Flush();
return true;
}
catch (Exception ex)
{
XTrace.WriteException(ex);
return false;
}
}
/// <summary>释放</summary>
public void Dispose()
{
try { _cts.Cancel(); } catch { }
if (_server != null)
{
try { _server.Wait(500); } catch { }
}
_cts.Dispose();
_mutex.Dispose();
}
}
|