Skip to content
Bruce Wayne edited this page Nov 9, 2021 · 3 revisions

Create

const string identifier = @"Global\SingleInstance" // Change to your Guid or something unique
ISingleInstanceService singleInstance = new SingleInstanceService(identifier);
// You should create service as singleton!

Try register as single instance

if(singleInstance.TryStartSingleInstance())
{
    // Success
}
else
{
    // There is another program register as same the identifier
}

if(singleInstance.IsFirstInstance)
{
    // This is the first instance.
}
else
{
    // This is not the first instance.
}

Transfer message between instances

1. The first instance start listen server

if(singleInstance.IsFirstInstance)
{
    singleInstance.StartListenServer();
}

2. Subscribe actions to handle incoming message

singleInstance.Received.SelectMany(ServerResponseAsync).Subscribe(); //Async
async Task<Unit> ServerResponseAsync((string, Action<string>) receive)
{
    var (message, endFunc) = receive;
    // TODO handle message

    await Task.Delay(TimeSpan.FromSeconds(3)); // You may do some jobs

    endFunc("success"); // Send response
    return default;
}

3. The second instance send message to the first instance

ISingleInstanceService singleInstance2 = new SingleInstanceService(identifier);

string message; // Your message
string response = await singleInstance2.SendMessageToFirstInstanceAsync(message);
// TODO handle response

Release single instance before exiting

singleInstance.Dispose();