Check whether the program is started and mutex is abnormal in C #.

Source: Internet
Author: User

Background]

In a recent project, I am in charge of the client module. Requirement: when starting the client, you need to determine whether the client has been started (Singleton ). So I decided to use mutex to implement this function. The Code is as follows:

Bool initiallyowned = true; bool iscreated; mutex M = new mutex (initiallyowned, "XXXXX", out iscreated); If (! (Initiallyowned & iscreated) {common. messageex. MSG ("the client has been started! "); Return ;}

In most cases, this function can be used to determine whether the client has been started.

[New requirements]

Nnd, one day there is a need for metamorphosis (BT). After the main form of the client pops up a sub-form, the sub-form needs to be minimized, while the sub-form needs to be minimized at the same time, when the main form is restored, the sub-form is restored (I really want to say, your uncle, the operating system has never met such a Bt requirement ).

[Mutex exception]

After some hard work, we finally achieved the BT demand. Occasionally, when a subform pops up on the client, the system is minimized, and then I start a new client. I was scared at the moment ---- nnd was able to start normally.

[Solution]

Finally, after debugging the program, I found that when the client has been started and is in the process of the above operations, I can start the client again and mutex can be created. Therefore, I can only perform the following operations (Singleton ):

Int I = 0; Process [] pros = process. getprocesses (); foreach (PROCESS p in PROs) {If (P. processname. Equals ("XXXXX "))
{
++ I;
}
If (I> 1) {break ;}
}

If (I> 1)
{
Common. messageex. MSG ("the client has been started! ");
Return;
}

[Why can't mutex judge]

As for why mutex cannot be judged, I have not figured it out yet. I hope to share this blog with you !!!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.