Skip to content

Commit

Permalink
Added a mutex to make sure only one instance of RepoM can be running.
Browse files Browse the repository at this point in the history
  • Loading branch information
coenm committed Sep 4, 2024
1 parent 3352f53 commit 6fcdec1
Showing 1 changed file with 54 additions and 1 deletion.
55 changes: 54 additions & 1 deletion src/RepoM.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace RepoM.App;
using RepoM.App.i18n;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.Services.WebApi;
using RepoM.Api.Plugins;
using RepoM.App.Plugins;
using Serilog;
Expand All @@ -28,6 +29,7 @@ namespace RepoM.App;
/// </summary>
public partial class App : Application
{
private static Mutex? _mutex;
private static IRepositoryMonitor? _repositoryMonitor;
private TaskbarIcon? _notifyIcon;
private ModuleService? _moduleService;
Expand All @@ -37,6 +39,11 @@ public partial class App : Application
[STAThread]
public static void Main()
{
if (IsAlreadyRunning())
{
return;
}

Thread.CurrentThread.Name ??= "UI";
var app = new App();
app.InitializeComponent();
Expand Down Expand Up @@ -109,7 +116,9 @@ protected override void OnExit(ExitEventArgs e)

// #pragma warning disable CA1416 // Validate platform compatibility
_notifyIcon?.Dispose();
// #pragma warning restore CA1416 // Validate platform compatibility
// #pragma warning restore CA1416 // Validate platform compatibility

ReleaseAndDisposeMutex();

base.OnExit(e);
}
Expand Down Expand Up @@ -149,5 +158,49 @@ private static void UseRepositoryMonitor(Container container)
_repositoryMonitor.Observe();
}

private static bool IsAlreadyRunning()
{
bool createdNew;

try
{
_mutex = new Mutex(true, "Local\\github.com/coenm/RepoM", out createdNew);
}
catch (Exception)
{
return true;
}

if (!createdNew)
{
_mutex.Dispose();
_mutex = null;
return true;
}

return false;
}

private static void ReleaseAndDisposeMutex()
{
try
{
_mutex?.ReleaseMutex();
}
catch (Exception)
{
// ignore
}

try
{
_mutex?.Dispose();
}
catch (Exception)
{
// ignore
}
}

public static string? AvailableUpdate { get; private set; } = null;
}

0 comments on commit 6fcdec1

Please sign in to comment.