Reputation: 321
i'm trying to prevent a Silverlight OOB App from opening twice, but i have no idea how.
I tried with creating a FileStream direct after app launch with "FileShare.None", to throw an error when the App is open twice and tries to open the file, but its ugly and doesn't work because the FileStream seems to be released after about 30 seconds..
FileStream s2 = new FileStream(path, FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.None);
Any idea how i could approach this?
Thanks, phil
Upvotes: 0
Views: 78
Reputation: 95
One way to achieve this is to use the local messaging channel between Silverlight applications. This scenario is mentioned in the MSDN, I will expand a little bit more here.
The LocalMessageReceiver class allow you to register to a messaging service primarily intended to communicate between different Silverlight applications.
The trick is that you can only register once with the same name in a particular scope. So as a consequence, if the first instance registers itself using your application name, any other instance doing the same afterwards will trigger an exception. Then you just have to catch that exception and deal with it, depending on what you want to do (close the instance, display a message, etc.)
Here's the code I use:
private bool CheckSingleInstance()
{
try
{
var receiver = new LocalMessageReceiver("application name", ReceiverNameScope.Global, LocalMessageReceiver.AnyDomain);
receiver.Listen();
return true;
}
catch (ListenFailedException)
{
// A listener with this name already exists
return false;
}
}
An advantage of this solution is that it works whether your instances are in-browser or out-of-browser.
Upvotes: 1