Skip to content

Commit

Permalink
simplified id for single instance
Browse files Browse the repository at this point in the history
  • Loading branch information
d2phap committed Mar 17, 2024
1 parent a744d82 commit 3a997cc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,15 @@ public void Dispose()

private Mutex? _mutex;
private readonly bool _ownsMutex;
private readonly Guid _id = Guid.Empty;
private readonly string _id = string.Empty;


/// <summary>
/// Indicates whether this is the first instance of this application.
/// </summary>
public bool IsFirstInstance => _ownsMutex;


/// <summary>
/// Event raised when arguments are received from successive instances.
/// </summary>
Expand All @@ -73,10 +74,10 @@ public void Dispose()
/// Enforces single instance for an application.
/// </summary>
/// <param name="id">An identifier unique to this application.</param>
public SingleInstance(Guid id)
public SingleInstance(string id)
{
_id = id;
_mutex = new Mutex(true, id.ToString(), out _ownsMutex);
_mutex = new Mutex(true, id, out _ownsMutex);
}


Expand All @@ -92,7 +93,7 @@ public async Task<bool> PassArgsToFirstInstanceAsync(string[] args)

try
{
using var client = new NamedPipeClientStream(_id.ToString());
using var client = new NamedPipeClientStream(_id);
using var writer = new StreamWriter(client);

await client.ConnectAsync(200).ConfigureAwait(false);
Expand Down Expand Up @@ -132,7 +133,7 @@ private void ListenForArgs(object? state)
{
try
{
using var server = new NamedPipeServerStream(_id.ToString());
using var server = new NamedPipeServerStream(_id);
using var reader = new StreamReader(server);
server.WaitForConnection();

Expand All @@ -147,7 +148,7 @@ private void ListenForArgs(object? state)
}
}

ThreadPool.QueueUserWorkItem(new(CallOnArgsReceived), args.ToArray());
ThreadPool.QueueUserWorkItem(CallOnArgsReceived, args.ToArray());
}
catch (IOException) { } // Pipe was broken
finally
Expand Down
6 changes: 2 additions & 4 deletions Source/ImageGlass/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ namespace ImageGlass;

internal static class Program
{
public static string APP_GUID => "{f2a83de1-b9ac-4461-81d0-cc4547b0b27b}";
public static string APP_SINGLE_INSTANCE_ID => "{f2a83de1-b9ac-4461-81d0-cc4547b0b27b}";


/// <summary>
Expand Down Expand Up @@ -178,10 +178,8 @@ private static void RunAppInstances()
}
else
{
var guid = new Guid(APP_GUID);

// single instance is required
using var instance = new SingleInstance(guid);
using var instance = new SingleInstance(APP_SINGLE_INSTANCE_ID);
if (instance.IsFirstInstance)
{
instance.ArgsReceived += Instance_ArgumentsReceived;
Expand Down

0 comments on commit 3a997cc

Please sign in to comment.