This article is a mirror article of machine translation, please click here to jump to the original article.

View: 24385|Reply: 4

[Source] C# programs only allow one instance to run the correct code

[Copy link]
Posted on 12/10/2016 2:55:50 PM | | | |


I wrote a traffic monitoring software that I want the computer to run only once, and the code is as follows:



Find, immediately, click on the software, it will prompt "An instance has been run", but,After waiting for 30 seconds, then click on the software, and it runs successfully againOnce !!

It's a pity.The above code is fine in DEBUG mode, but it doesn't work in RELEASE.
The problem is that Mutex is declared as a local variable, and in relese mode due to optimization issues, possibly because the compiler thinks Mutex is no longer used

used, recycled, tested by myself,

Put Mutex on top and set it as a static variable to !!!RightThe code is as follows:





Score

Number of participants1MB+1 contribute+1 Collapse reason
A little novice who loves to learn + 1 + 1 Like one!

See all ratings





Previous:C# only allows the correct writing of one instance of the application to run
Next:How to set up software boot automatically.
 Landlord| Posted on 12/10/2016 3:02:58 PM |
Static fields are not recycled by the GC, static fields are allocated in the Loader heap, non-GC heap, and are not controlled by the GC.

Static members (of static classes or not) are only recycled when they reach AppDomain.UnLoad. Static classes are only allowed to have static members
Posted on 12/6/2017 11:48:05 AM |
Learned, thank you for sharing
 Landlord| Posted on 2/23/2018 2:59:01 PM |
Other implementations:

Startup method:



 Landlord| Posted on 10/3/2025 4:10:11 PM |
.NET/C# implements program singleton based on Mutex and MemoryMappedFile
https://www.itsvse.com/thread-10808-1-1.html
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com