Skip to content

Commit e2da44c

Browse files
committed
enhance: use Mutex to force running SourceGit in singleton mode
Signed-off-by: leo <[email protected]>
1 parent 0acbe3e commit e2da44c

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

src/Models/IpcChannel.cs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class IpcChannel : IDisposable
1010
{
1111
public bool IsFirstInstance
1212
{
13-
get => _server != null;
13+
get => _isFirstInstance;
1414
}
1515

1616
public event Action<string> MessageReceived;
@@ -19,14 +19,19 @@ public IpcChannel()
1919
{
2020
try
2121
{
22-
_server = new NamedPipeServerStream(
23-
"SourceGitIPCChannel",
24-
PipeDirection.In,
25-
1,
26-
PipeTransmissionMode.Byte,
27-
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance);
28-
_cancellationTokenSource = new CancellationTokenSource();
29-
Task.Run(StartServer);
22+
_singletonMutex = new Mutex(false, "SourceGit_2994509B-4906-4A48-9A45-55C1836A8208", out _isFirstInstance);
23+
24+
if (_isFirstInstance)
25+
{
26+
_server = new NamedPipeServerStream(
27+
"SourceGitIPCChannel",
28+
PipeDirection.In,
29+
-1,
30+
PipeTransmissionMode.Byte,
31+
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
32+
_cancellationTokenSource = new CancellationTokenSource();
33+
Task.Run(StartServer);
34+
}
3035
}
3136
catch
3237
{
@@ -60,6 +65,7 @@ public void SendToFirstInstance(string cmd)
6065
public void Dispose()
6166
{
6267
_cancellationTokenSource?.Cancel();
68+
_singletonMutex.Dispose();
6369
}
6470

6571
private async void StartServer()
@@ -83,6 +89,8 @@ private async void StartServer()
8389
}
8490
}
8591

92+
private Mutex _singletonMutex = null;
93+
private bool _isFirstInstance = false;
8694
private NamedPipeServerStream _server = null;
8795
private CancellationTokenSource _cancellationTokenSource = null;
8896
}

0 commit comments

Comments
 (0)