Consider I want to run APP.exe 2 times, respectively. I need to define a variable to be shared in all application domains. for example I have a integer X in my code, I changed it in app.exe(1)(means first run of app) and then want to use it in app.exe(2)(second run of same app). But each time the variables initialize and each run app have IT'S X. I know this is not happen in web application if I set Static for X, but for WPF and Winform, the application domains are different and the X is different. Actually my real problem is locking on entity model. I want to prevent accessing to model by each instance of application. I know it is possible by SQL but I want to Lock a Common Shared variable in C#.
EDITED
I used Mutex but the problem still remains. See my example please
private static Mutex mut = new Mutex();
public void Dopessimistic(int id , string name)
{
mut.WaitOne();
{
MessageBox.Show("nm1");
}
}
I Run my app.exe 2 times. I expect that The message will be shown just one time, because I do not release the mutex, but for every run of app.exe it works and shows the message. Actually the Mutex seems not to be shared among All applications and each run has its own mutex separately!!
You should use:
private static Mutex mut = new Mutex(false,"MyAppMutex");
public void Dopessimistic(int id , string name) {
In that way you will create a systemwide
Mutex
.If you create an unnamed one (like you did in your code), it will be local to your app.
Note: if one app takes ownership of the
Mutex
and is closed without releasing it, theMutex
becomes 'abandoned' and the next thread waiting for theMutex
will get ownership. In your test this would mean that the second instance of App.exe gets to show its text as well, but only after the first instance has been closed.