473,700 Members | 2,484 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mutex and single instance console app ?

PL

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.Threadin g;

namespace MutexTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Mutex appMutex = new Mutex(false, "Applicatio n");
if(appMutex.Wai tOne(0, false))
{
System.Console. WriteLine("Runn ing");
System.Console. ReadLine();
}
else
{
System.Console. WriteLine("App already running !");
}
}
}
}

The only difference between this test and my app is that I have more
code where I print the "Running" message, no other difference, still
it doesn't work !

I've read numerous other threads saying similar things but no solutions.
Could anyone shed some light as to why this does not work ?

Thank you
PL.
Nov 22 '05 #1
4 3770
PL

This is amazing, I solved it by putting the appMutex variable outside main
and make it static, now it works as expected.

I assume it's because somehow the mutex is garbage collected and therefore
released before it should be.

This seems like a bug to me, I would assume the compiler does some strange
optimization here since it seem to work with the local variable in debug
mode.

PL.

"PL" <pb****@yahoo.s e> skrev i meddelandet
news:uC******** ******@TK2MSFTN GP12.phx.gbl...

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.Threadin g;

namespace MutexTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Mutex appMutex = new Mutex(false, "Applicatio n");
if(appMutex.Wai tOne(0, false))
{
System.Console. WriteLine("Runn ing");
System.Console. ReadLine();
}
else
{
System.Console. WriteLine("App already running !");
}
}
}
}

The only difference between this test and my app is that I have more
code where I print the "Running" message, no other difference, still
it doesn't work !

I've read numerous other threads saying similar things but no solutions.
Could anyone shed some light as to why this does not work ?

Thank you
PL.

Nov 22 '05 #2
No, this is not a bug in .NET, it's a "users bug". The JIT is free to mark
objects that are no longer referenced in the code path eligible for GC, the
fact that the underlying handle is a system wide kernel object that should
be kept for the duration of the program is not the JIT business.
To prevent premature collection of the Mutex you could wrap your code in a
using block (yes, Mutex derives from a Disposable), this is more elegant
than using a static.

using(System.Th reading.Mutex m = new System.Threadin g.Mutex(true,
"YourNameHere") )
{
// Your code here
} // Done with the Mutex, the handle can be released

Willy.

"PL" <pb****@yahoo.s e> wrote in message
news:uC******** ******@TK2MSFTN GP12.phx.gbl...

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.Threadin g;

namespace MutexTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Mutex appMutex = new Mutex(false, "Applicatio n");
if(appMutex.Wai tOne(0, false))
{
System.Console. WriteLine("Runn ing");
System.Console. ReadLine();
}
else
{
System.Console. WriteLine("App already running !");
}
}
}
}

The only difference between this test and my app is that I have more
code where I print the "Running" message, no other difference, still
it doesn't work !

I've read numerous other threads saying similar things but no solutions.
Could anyone shed some light as to why this does not work ?

Thank you
PL.

Nov 22 '05 #3
PL

Thank you, the using block worked fine as well and is as you say more
elegant.

I guess what confuses me here is the definition of "not referenced", if I
have a local
variable in Main that do not change you would think it stays referenced
during the
whole lifetime of the program but apparently not.

I guess I need to read up on the garbage collector.

Considering all the examples I found on the net on how to do this that
didn't use a static variable,
a using block or gc.keepalive it seems to me like only more memory intensive
programs experience
this issue which makes it somewhat dangerous.

PL.
"Willy Denoyette [MVP]" <wi************ *@pandora.be> skrev i meddelandet
news:eH******** ******@TK2MSFTN GP15.phx.gbl...
No, this is not a bug in .NET, it's a "users bug". The JIT is free to mark
objects that are no longer referenced in the code path eligible for GC,
the fact that the underlying handle is a system wide kernel object that
should be kept for the duration of the program is not the JIT business.
To prevent premature collection of the Mutex you could wrap your code in a
using block (yes, Mutex derives from a Disposable), this is more elegant
than using a static.

using(System.Th reading.Mutex m = new System.Threadin g.Mutex(true,
"YourNameHere") )
{
// Your code here
} // Done with the Mutex, the handle can be released

Willy.

Nov 22 '05 #4

"PL" <pb****@yahoo.s e> wrote in message
news:eP******** ******@TK2MSFTN GP10.phx.gbl...

Thank you, the using block worked fine as well and is as you say more
elegant.

I guess what confuses me here is the definition of "not referenced", if I
have a local
variable in Main that do not change you would think it stays referenced
during the
whole lifetime of the program but apparently not.


This is something to watch out for. A local variable holding a reference to
an object in the managed heap, will be set to null by the JIT compiler
(running in non-debug mode) when it's no longer used in the scope of the
method. Now in the case of a Mutex, the underlying OS handle will only be
released when the finalizer comes along, which can be a long time after the
reference was null'ed. To take control of the lifetime of such an unmanaged
resource you should adopt the disposing pattern and wrap your code in a
using block, just like I've done with the using block.

Willy.
Nov 22 '05 #5

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

Similar topics

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
4775
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
20
6480
by: Michael A. Covington | last post by:
See: http://www.ai.uga.edu/mc/SingleInstance.html While attempting to use a mutex to allow only one instance of my app to run at a time (Recipe 4.12 in C# Programmer's Cookbook), I found that if the mutex is in a local variable in Main(), and my program launches any windows before Application.Run(), it will lose the mutex upon doing so. It shouldn't, as far as I can see. Moving the mutex variable outside Main() and making it static...
16
3156
by: Ed Sutton | last post by:
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
3
6397
by: ano | last post by:
How to reset Mutex.ReleaseMutex()? I can't call Mutex.WaitOne() again because the Mutex status seem to be fix to ReleaseMutex(). Do I need to create new Mutex() every time after ReleaseMutex()? Thanks
2
6229
by: tony.newsgrps | last post by:
Hi there, I'm trying to understand the impact of killing a process that owns a system mutex (used to ensure there is only 1 instance of my program running) Here is my code pretty much: try { mutex=new System.Threading.Mutex( true, mutexName, out createdNew)
1
2060
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
2
1411
by: =?Utf-8?B?Q2F2ZXk=?= | last post by:
Hello, Encountering a issue where I define a mutex to enforce a single instance of an application. It works well under Debug but switching to release it fails everytime.. bool exclusive = false; Mutex m = new Mutex(true, "SOEIFrameworkMutex", out exclusive); if (exclusive)
2
3750
by: cj | last post by:
I take it a mutex is like a synclock but visible outside the program?
11
3686
by: Lamont Sanford | last post by:
Given an object of type Mutex, what method or property should be called to determine if it is currently owned? I could call WaitOne(0,false) -- and if the return value is false, I could deduce that the Mutex is already owned... but this has the unwanted side effect of seizing ownership of the Mutex in the case where the Mutex is NOT already owned. I'm looking for something like an "IsOwned" property.
0
8728
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8647
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
9076
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
8974
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
7813
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5903
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();...
1
3092
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
2
2392
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2030
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.