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