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
…#143)

* Added a mutex to make sure only one instance of RepoM can be running.

* cleanup
  • Loading branch information
coenm authored Sep 4, 2024
1 parent 3352f53 commit 89d2ed9
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/RepoM.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,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 +38,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 @@ -111,6 +117,8 @@ protected override void OnExit(ExitEventArgs e)
_notifyIcon?.Dispose();
// #pragma warning restore CA1416 // Validate platform compatibility

ReleaseAndDisposeMutex();

base.OnExit(e);
}

Expand Down Expand Up @@ -149,5 +157,47 @@ private static void UseRepositoryMonitor(Container container)
_repositoryMonitor.Observe();
}

private static bool IsAlreadyRunning()
{
try
{
_mutex = new Mutex(true, "Local\\github.com/coenm/RepoM", out var createdNew);

if (createdNew)
{
return false;
}
}
catch (Exception)
{
return true;
}

_mutex.Dispose();
_mutex = null;
return true;
}

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 89d2ed9

Please sign in to comment.