473,765 Members | 1,964 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Did GC eat my mutex? Why did Mutex need to be static?

I use a mutex to disallow starting a second application instance. This
did not work in a release build until I made it static member of my
MainForm class.

In a debug build, first instance got ownership, second did not and
terminated. In a release build, the second instance *also* got
ownership. I "fixed" it by making the mutex a static member of my
MainForm class.

Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?

I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}
Nov 16 '05 #1
16 3160
Ed Sutton <S_************ *@nomadics.com> wrote:
Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?
Yes - it's quite at liberty to do so.
I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}


Put a GC.KeepAlive(mu tex); at the end of your try block, and all should
be well.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
I just discovered it works in a release build if I add a mutex.Close()
after Application.Run ().

It appears I need to learn about how the GC works.

-Ed
Ed Sutton wrote:
I use a mutex to disallow starting a second application instance. This
did not work in a release build until I made it static member of my
MainForm class.

In a debug build, first instance got ownership, second did not and
terminated. In a release build, the second instance *also* got
ownership. I "fixed" it by making the mutex a static member of my
MainForm class.

Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?

I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}

Nov 16 '05 #3
Ed Sutton <S_************ *@nomadics.com> wrote:
I just discovered it works in a release build if I add a mutex.Close()
after Application.Run ().

It appears I need to learn about how the GC works.


Basically the GC can tell that the mutex variable isn't used again
after it's created, so it's no longer considered "live".

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
Hi John,

Thank you very much for your reply.
Basically the GC can tell that the mutex variable isn't used again
after it's created, so it's no longer considered "live".


How you described it sounds very efficient. I guess my C++ experience
was leading me to think it would not be garbage collected until it went
out of scope. In most cases, I believe this type of thinking has not
gotten me into trouble.

However, I am beginning to think I have been lucky. I am concerned
about objects that I share between threads being garbage collected. My
objects that are declared static are ok. But I am starting to be
concerned about other objects that may not be static.

-Ed
Nov 16 '05 #5
Hi,

The garbage collector only collects objects which don't have at least one
valid reference. In your case there seems to be a valid reference because
Application.Run doens't return until the app quits and so mutex is a valid
though local variable.

The "problem" is with the compiler, it is the compiler that can see that you
don't use the created object. So in release build when optimizing, it sees
that mutex isn't used. Therefore there won't even be a local variable
"mutex" in the release build (ilasm). It creates the mutex but it doesn't
store its reference anywhere, which is the reason the gc collects it.

Putting mutex.Close after Application.Run is a good solution to prevent the
unwanted optimalization.
HTH,
greetings
"Ed Sutton" <S_************ *@nomadics.com> wrote in message
news:eM******** *****@TK2MSFTNG P11.phx.gbl...
I use a mutex to disallow starting a second application instance. This
did not work in a release build until I made it static member of my
MainForm class.

In a debug build, first instance got ownership, second did not and
terminated. In a release build, the second instance *also* got
ownership. I "fixed" it by making the mutex a static member of my
MainForm class.

Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?

I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}

Nov 16 '05 #6
Ed Sutton <S_************ *@nomadics.com> wrote:
Basically the GC can tell that the mutex variable isn't used again
after it's created, so it's no longer considered "live".


How you described it sounds very efficient. I guess my C++ experience
was leading me to think it would not be garbage collected until it went
out of scope. In most cases, I believe this type of thinking has not
gotten me into trouble.

However, I am beginning to think I have been lucky. I am concerned
about objects that I share between threads being garbage collected. My
objects that are declared static are ok. But I am starting to be
concerned about other objects that may not be static.


The only time this is a concern is when an object being garbage
collected (or really, finalized - garbage collection itself is very
unlikely to cause you any problems) causes some side-effect which is
undesirable. Aside from this mutex case (and similar ones, eg "having a
file open for locking"), I don't think it's likely to be a problem for
you.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
Ed Sutton wrote:
I use a mutex to disallow starting a second application instance. This
did not work in a release build until I made it static member of my
MainForm class.

In a debug build, first instance got ownership, second did not and
terminated. In a release build, the second instance *also* got
ownership. I "fixed" it by making the mutex a static member of my
MainForm class.

Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?

I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}

The correct solution is:

[STAThread]
static void Main()
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
using(Mutex mutex = new Mutex(true, safeName, out firstInstance))
{
if(false == firstInstance)
return;

try
{
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}
}
--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/tools/leakfinder.asp
Do you need daily reports from your server ?
http://sourceforge.net/projects/srvreport/
Nov 16 '05 #8
Hmmm, How can the GC collect it when it's reference is not stored somewhere?
Did you actually look at the IL?

Not sure if you aren't confusing compiler with Jitter, but this has nothing
to do with the compiler and compiler optimizations, it's actually the Jitter
that 'sees' that the reference is not longer needed when Application.Run
returns, so it sets the reference to null when calling Application run, so
it's a runtime optimization.
When running in the debugger, the Jitter doesn't perform any kind of
"optimizations' , as such the mutex is maintained until main goes out of
scope.

Willy.

"BMermuys" <so*****@someon e.com> wrote in message
news:eB******** ******@TK2MSFTN GP12.phx.gbl...
Hi,

The garbage collector only collects objects which don't have at least one
valid reference. In your case there seems to be a valid reference because
Application.Run doens't return until the app quits and so mutex is a valid
though local variable.

The "problem" is with the compiler, it is the compiler that can see that
you
don't use the created object. So in release build when optimizing, it
sees
that mutex isn't used. Therefore there won't even be a local variable
"mutex" in the release build (ilasm). It creates the mutex but it doesn't
store its reference anywhere, which is the reason the gc collects it.

Putting mutex.Close after Application.Run is a good solution to prevent
the
unwanted optimalization.
HTH,
greetings
"Ed Sutton" <S_************ *@nomadics.com> wrote in message
news:eM******** *****@TK2MSFTNG P11.phx.gbl...
I use a mutex to disallow starting a second application instance. This
did not work in a release build until I made it static member of my
MainForm class.

In a debug build, first instance got ownership, second did not and
terminated. In a release build, the second instance *also* got
ownership. I "fixed" it by making the mutex a static member of my
MainForm class.

Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?

I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}


Nov 16 '05 #9
Hi,

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
Hmmm, How can the GC collect it when it's reference is not stored somewhere?

Maybe because there is a *managed heap* which keeps track of all created
objects. The GC checks each object on the managed heap to see if it has any
valid references, if there aren't it cleans up the object.
Did you actually look at the IL?

Not sure if you aren't confusing compiler with Jitter, but this has nothing to do with the compiler and compiler optimizations, it's actually the Jitter that 'sees' that the reference is not longer needed when Application.Run
returns, so it sets the reference to null when calling Application run, so
it's a runtime optimization.
When running in the debugger, the Jitter doesn't perform any kind of
"optimizations' , as such the mutex is maintained until main goes out of
scope.
I wouldn't answer such a question before looking at the ILASM. I wonder if
you looked ? And yes I mean the compiler and not the jitter and do know the
difference.

If you look at release ilasm you will see that the reference from the
created mutex isn't stored anywhere, there isn't even a local variable
'mutex' . This is a compiler optimalization that happens only in release
build.
Greetings


Willy.

"BMermuys" <so*****@someon e.com> wrote in message
news:eB******** ******@TK2MSFTN GP12.phx.gbl...
Hi,

The garbage collector only collects objects which don't have at least one valid reference. In your case there seems to be a valid reference because Application.Run doens't return until the app quits and so mutex is a valid though local variable.

The "problem" is with the compiler, it is the compiler that can see that
you
don't use the created object. So in release build when optimizing, it
sees
that mutex isn't used. Therefore there won't even be a local variable
"mutex" in the release build (ilasm). It creates the mutex but it doesn't store its reference anywhere, which is the reason the gc collects it.

Putting mutex.Close after Application.Run is a good solution to prevent
the
unwanted optimalization.
HTH,
greetings
"Ed Sutton" <S_************ *@nomadics.com> wrote in message
news:eM******** *****@TK2MSFTNG P11.phx.gbl...
I use a mutex to disallow starting a second application instance. This
did not work in a release build until I made it static member of my
MainForm class.

In a debug build, first instance got ownership, second did not and
terminated. In a release build, the second instance *also* got
ownership. I "fixed" it by making the mutex a static member of my
MainForm class.

Did the garbage collector eat my mutex because it is not referenced
again after Application.Run is called?

I could not reproduce this on a new simple WinForm project; I tried
making all the project setting the same. Here's the code that did not
work in release build.

[STAThread]
static void Main()
{
try
{
bool firstInstance = false;
string safeName = Application.Use rAppDataPath.Re place(@"\","_") ;
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run (new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}



Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2251
by: Rocky | last post by:
I am using the following piece of code to ensure that my application only runs once, however I have a few questions about it. static Mutex m_Mutex; << in c# I assume that when the methods are static, so are the private members public static void Run(Form mainForm) { if(IsFirstInstance()) {
4
329
by: PL | last post by:
I simply cannot get this to work with my current project, if I create a test project with only the code below it works fine but in my real app it still allows two instances. using System; using System.Threading; namespace MutexTest {
2
4780
by: Martin Maat | last post by:
Hi. I want to use the same mutex in different classes (web pages in an ASP.NET application). In global.asax.cs, the class that starts up first, I create a Mutex like this: static private Mutex mtxBezoeken = new Mutex(false, "bezoeken"); which compiles and executes just fine. Then in another page I want to write to a file that may also be accessed by global.asax.cs so I want access to
1
442
by: Kris | last post by:
I want to set a mutex in one windows account and allow another windows account to access this mutex. For testing I have two forms that create a mutex using the C# mutex class. I am logging into Windows XP as "User1" and creating and locking the mutex from "User1" using the 1st form. I then use the "switch users" function to log in as "User2" and run the 2nd form and attempt to create the mutex (using the same name). When I try this I get...
11
3084
by: Tyler Sample | last post by:
I've been having strange thread conflicts, and after moving the relevant mutex higher and higher I've finally determined that the mutex doesn't seem to be working at all. Here is the relevant code: private static Mutex previewMutex = new Mutex(); private static void preview (string source, string target) {
7
1824
by: Ken Varn | last post by:
I am working in managed C++. I have a Mutex object in which I need to replace the Handle property with a new handle. The new handle is being constructed using Win32 CreateMutex call. I need to call the Win32 version in order to set the security descriptor for the mutex, which is not natively supported in .NET Framework 1.1. I always get a little nervous about resource leaks when trying to bridge Win32 with .NET, so I want to make sure...
1
2063
by: cold80 | last post by:
I'm trying to check in my application if another instance of it is already running. I found many code snippets on the net that make use of a named mutex to do this check, but I can't make it work on visual basic. Actually, it works sometimes and sometimes not. The code I'm trying is: Namespace WindowsApplication2 Public Class Form1 Inherits Form
3
5589
by: NaeiKinDus | last post by:
Hello, i'm trying to program a thread that would be locked (by a mutex) and that would only be unlocked once that a function (generating data) is done. The purpose is to generate data, and unlock the mutex in order to activate the thread once the data is generated. I have to do it this way, i can only call the thread if the data are generated. ******************************************************** step 1: initialize the mutex
2
4867
by: tshad | last post by:
I am running a program as a Windows service which works fine. I am using a Mutex to prevent multiple threads from from accessing my log text file at the same time. It works fine in the Service: In my AppSettings class: public static Mutex mutexPrinterFile; In my program:
0
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9955
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9833
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7378
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.