Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Detecting duplicate instances of a running Silverlight application

This is a short tip for constraining your Silverlight applications to a single instance, something that’s quite popular in the desktop applications world. What you want to do is allow only the first instance of your application while rejecting all subsequent instances.

Silverlight 3 introduced a way for applications to communicate between each other, either on the same page or instantiated on a different browser instances (works even with Installed/OOB apps). The communication is performed by sender and receiver classes, which exchange messages through named channels. Each receiver must register a unique name for the channel or an exception will be thrown.

And that’s the trick. Listening on a specific named channel will act like a mutex. By catching the ListenFailed exception you get an option to display appropriate message or launch a different version of the application. All the work is done in App.Xaml.cs file:

private void Application_Startup(object sender, StartupEventArgs e)
{
    try
    {
        receiver = new LocalMessageReceiver("singleinstance");
        receiver.Listen();
        this.RootVisual = new MainPage();
    }
    catch (ListenFailedException)
    {
        this.RootVisual = new DuplicateInstancePage();
    }
}

The test project is available through here.