BililiveRecorder/BililiveRecorder.WPF/SingleInstance.cs

76 lines
2.6 KiB
C#
Raw Normal View History

2020-11-27 18:51:02 +08:00
using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
2021-02-23 18:03:37 +08:00
#nullable enable
2020-11-27 18:51:02 +08:00
namespace BililiveRecorder.WPF
{
public static class SingleInstance
{
2021-02-23 18:03:37 +08:00
private static Mutex? singleInstanceMutex;
private static IpcServerChannel? channel;
2020-11-27 18:51:02 +08:00
2021-02-23 18:03:37 +08:00
public static event EventHandler? NotificationReceived;
2020-11-27 18:51:02 +08:00
public static bool CheckMutex(string path)
{
const string RemoteServiceName = "SingleInstanceApplicationService";
var b64path = Convert.ToBase64String(Encoding.UTF8.GetBytes(path)).Replace('+', '_').Replace('/', '-');
var identifier = "BililiveRecorder:SingeInstance:" + b64path;
singleInstanceMutex = new Mutex(true, identifier, out var createdNew);
if (createdNew)
{
channel = new IpcServerChannel(new Dictionary<string, string>
{
["name"] = identifier,
["portName"] = identifier,
["exclusiveAddressUse"] = "false"
}, new BinaryServerFormatterSinkProvider
{
TypeFilterLevel = TypeFilterLevel.Full
});
ChannelServices.RegisterChannel(channel, true);
RemotingServices.Marshal(new IPCRemoteService(), RemoteServiceName);
}
else
{
ChannelServices.RegisterChannel(new IpcClientChannel(), true);
var remote = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), $"ipc://{identifier}/{RemoteServiceName}");
remote?.Notify();
}
return createdNew;
}
public static void Cleanup()
{
if (channel != null)
{
ChannelServices.UnregisterChannel(channel);
channel = null;
}
singleInstanceMutex?.Close();
singleInstanceMutex = null;
2020-11-27 18:51:02 +08:00
}
private static void ActivateFirstInstanceCallback() => NotificationReceived?.Invoke(null, EventArgs.Empty);
private class IPCRemoteService : MarshalByRefObject
{
public void Notify() => Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)ActivateFirstInstanceCallback);
2021-02-23 18:03:37 +08:00
public override object? InitializeLifetimeService() => null;
2020-11-27 18:51:02 +08:00
}
}
}