enhance: use Mutex to force running SourceGit in singleton mode

Signed-off-by: leo <longshuang@msn.cn>
This commit is contained in:
leo 2025-04-15 09:35:16 +08:00
parent 0acbe3e487
commit e2da44c8fd
No known key found for this signature in database

View file

@ -10,7 +10,7 @@ namespace SourceGit.Models
{
public bool IsFirstInstance
{
get => _server != null;
get => _isFirstInstance;
}
public event Action<string> MessageReceived;
@ -19,14 +19,19 @@ namespace SourceGit.Models
{
try
{
_server = new NamedPipeServerStream(
"SourceGitIPCChannel",
PipeDirection.In,
1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance);
_cancellationTokenSource = new CancellationTokenSource();
Task.Run(StartServer);
_singletonMutex = new Mutex(false, "SourceGit_2994509B-4906-4A48-9A45-55C1836A8208", out _isFirstInstance);
if (_isFirstInstance)
{
_server = new NamedPipeServerStream(
"SourceGitIPCChannel",
PipeDirection.In,
-1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
_cancellationTokenSource = new CancellationTokenSource();
Task.Run(StartServer);
}
}
catch
{
@ -60,6 +65,7 @@ namespace SourceGit.Models
public void Dispose()
{
_cancellationTokenSource?.Cancel();
_singletonMutex.Dispose();
}
private async void StartServer()
@ -83,6 +89,8 @@ namespace SourceGit.Models
}
}
private Mutex _singletonMutex = null;
private bool _isFirstInstance = false;
private NamedPipeServerStream _server = null;
private CancellationTokenSource _cancellationTokenSource = null;
}