Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to allow only one instance of my application. So using Mutex seems to be a good possibility to achieve that. But all examples I found describe how to close the instance that was started secondary.

Is there a way to signal the first instance if a second instance starts using (System.Threading.)Mutex? Or is there another clean way to close the first instance of my application if a second instance starts?

Thanks!! :)

Gobble-G
Posted
Updated 11-Aug-10 7:45am
v2

Instead of a Mutex you could use a ManualResetEvent and have the first instance register a thread pool wait on it. When another instance starts it can attempt to open up the MRE, if it exists then it can set it which will signal the first instance to close and then reset it and then register it's thread pool wait on it.

Something like this:
C#
// all of this happens on startup obviously
bool createdNew = false;
EventWaitHandle instanceEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "MyInstanceEvent", out createdNew);
if (!createdNew)
{
    instanceEvent.Set();
}

instanceEvent.Reset();
ThreadPool.RegisterWaitForSingleObject(instanceEvent, (state, timedOut) =>
{
    instanceEvent.Close();

    // where this is the Form class
    this.Close(); 
}, null, Timeout.Infinite, true);
 
Share this answer
 
v2
Comments
Niklas L 12-Aug-10 4:59am    
Reason for my vote of 5
A good solution, but it will open a time window, between the event is set and the new event is created, where the application needs extra protection if the behavior is essential.
Yeah, this works great.

The only thing I had to add is a thread synchronization to close the application. As I use WPF I replaced your line:
this.Close();

by:
this.Dispatcher.Invoke(new Action(() => { Application.Current.Shutdown(); }));


Thank you very much! :)
 
Share this answer
 
Comments
Toli Cuturicu 12-Aug-10 8:41am    
Reason for my vote of 1
fake answer
DaveyM69 17-Aug-10 6:53am    
Reason for my vote of 4
Although the OP didin't specify or tag as WPF he has added a solution for that situation so counts as an answer as far as I'm concerned.
Gobble-G 17-Aug-10 14:55pm    
I'm sorry - I'm new to codeproject.com and not familiar with the manners. What's the problem with my answer? In my opinion my problem was not a specific WPF problem but rather a .NET problem. So why I had to tag as WPF? I'm also using SQL, several WSDL proxies, XML and a few third party libraries. Should I also tag these keywords? %-/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900