Click to See Complete Forum and Search --> : Window Application Main() life time?


sharong
March 22nd, 2005, 08:18 AM
I wrote some Windows application. in the Main() method of the project I use Mutex.
I was sure that that mutex will live during all the application run time. But it appears that the Mutex is CG after a while.

The following code is the code I'm using. I use it to make sure only one instance of my program is running, but there are cases that the ownership is obtained although there is already another application like this running:

[STAThread]
static void Main()
{
bool hasOwnership;
System.Threading.Mutex singelLogger = new System.Threading.Mutex(true, "MyApplication", out hasOwnership);if( ! hasOwnership )
{
MessageBox.Show(null, "The Mutex ownership is taken.\n\n Exiting!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Application.Run( new MyAppForm() );
}


How can that be?


Thanks
Sharon

Krzemo
March 22nd, 2005, 08:48 AM
It is a local variable - so it will be GC collected (by design).

To prevent this use "GC.KeepAlive(singelLogger);" after "Application.Run" line or use static class member variable instead of local variable.

Best regards,
Krzemo.

sharong
March 22nd, 2005, 08:52 AM
I did change is to static and it works.

But I just do not understand why it's collected by the GC. I know it's local variable, but it's in a static function that lives during all the program run time, so all it "local" variables should stay alive as well.

I'm I wrong?
Can you explain please.

------
Thanks
Sharon

Krzemo
March 22nd, 2005, 09:03 AM
But I just do not understand why it's collected by the GC It is local and unrefferenced variable - so GC will think that it is no longer needed :D .

Hope it helps.