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.



tweetmeme_url = 'http://tozon.info/blog/post/2009/10/31/Detecting-duplicate-instances-of-a-running-Silverlight-application.aspx'; tweetmeme_source = 'andrejt';
Avtor: Anonymous, objavljeno na portalu SloDug.si (Arhiv)

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.