How to define a common variable in all application domains by c#

203 views Asked by At

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!!

2

There are 2 answers

3
Johan Donne On BEST ANSWER

You should use:

private static Mutex mut = new Mutex(false,"MyAppMutex");

public void Dopessimistic(int id , string name) {

        mut.WaitOne();
        {
            MessageBox.Show("nm1");

        }

    }

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, the Mutex becomes 'abandoned' and the next thread waiting for the Mutex 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.

2
sakib rahman On

You can do it in many ways. you may pass your variable as form parameter-

private void button1_Click(object sender, EventArgs e)
{
        int X=5;
        Form2 frm2 = new Form2(X);
        frm2.Show();    
}

In second form just get the value -

 public Form2(int X)
    {
        InitializeComponent();
        textBox1.Text = X.ToString();

    }