当前位置:网站首页>CLR via C reading notes - single instance application
CLR via C reading notes - single instance application
2022-06-29 10:26:00 【zlbcdn】
scene
In actual use , There are cases where only one application is allowed to start .
effect
The effect is as follows : When starting the first , You can create an instance , When you create it again , Pop up the prompt box 

Solution
The code is as follows :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace CreateOnlyOne
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
bool creatNewOne = false;
using (new Semaphore(0, 1, "theOnlyOne", out creatNewOne))
{
if(creatNewOne)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show(" The program can only be started 1 individual , Currently started ! Unable to restart !");
}
}
}
}
}
analysis
1、 Only one instance can be created , Note that there needs to be a in the operating system layer “ a registration form ” The function of , Have already been posted , There will be records . therefore , When creating an instance , First judge whether there has been registration , If there is no , Then create an instance , Otherwise, a prompt will pop up .
2、Semaphore. The example of a parking lot can be used to illustrate Semaphore.
Take a parking lot as an example . For the sake of simplicity , Suppose there are only three parking spaces in the parking lot , At first, all three parking spaces were empty . At this time, if there are five cars at the same time , The gatekeeper allowed three of them unimpeded access , Then put down the car Block , The rest of the cars have to wait at the entrance , Later cars had to wait at the entrance . At this time , A car left the parking lot , When the doorman learned that , Open the car stop , Put in a , If you leave two more , You can put two more , So back and forth .
In this parking system , Parking spaces are public resources , Every car is like a thread , What the doorman does is signal quantity (Semaphore) The role of .
Further more , The characteristics of semaphores are as follows : A semaphore is a nonnegative integer ( Number of cars ), All threads through it ( vehicle ) All will subtract the integer by one ( It's for the use of resources, of course ), When the integer value is zero , All threads trying to pass through it will be waiting . In semaphores, we define two operations : Wait( wait for ) and Release( Release ). When a thread calls Wait( wait for ) In operation , It either passes through and then subtracts the semaphore by one , Or keep waiting , Until the semaphore is greater than one or timeout .Release( Release ) In fact, it is to perform the plus operation on the semaphore , Corresponds to the vehicle leaving the parking lot , This operation is called “ Release ” Because the addition operation actually releases the resources guarded by the semaphore .
Its constructors are as follows : 
In the constructor , There are two key points :
1、int initialCount: In the beginning when , The number of vehicles that the doorman announced could enter .MSDN Explanation above :The initial number of requests for the semaphore that can be granted concurrently. In the beginning , The amount a doorman can handle at a time .
2、int maximumCount: Maximum number of parking lots .
Semaphore Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SemaphoreExample
{
class Program
{
static Semaphore sem = new Semaphore(2, 2, "PackingSemaphore");
static void Main(string[] args)
{
for (int i = 0; i < 5;i++ )
{
Thread td = new Thread(recordPacking);
td.Name = string.Format(" vehicle {0}", i);
td.Start(td.Name);
}
Console.ReadKey();
}
static void recordPacking(object obj)
{
sem.WaitOne();
Console.WriteLine(obj.ToString()+" Enter the parking lot , Time :"+DateTime.Now.ToString());
Thread.Sleep(1500);
Console.WriteLine(obj.ToString() + " Get out of the parking lot , Time :" + DateTime.Now.ToString());
sem.Release();
}
}
}There is a sentence like this :
static Semaphore sem = new Semaphore(2, 2, “PackingSemaphore”);
representative , There are two parking spaces in the parking lot , You can enter two parking spaces at the same time . So the output is : 
When the above sentence , Turn into :
static Semaphore sem = new Semaphore(0, 2, “PackingSemaphore”);
Semaphore The number of requests that can be processed during initialization is 0, Vehicles cannot enter the parking lot .( It is equivalent to the doorman leaving his post without authorization at the beginning , So no matter how many cars are lined up , No one can get in ), As shown in the figure : 
Even in the above case , When the release statement is added .
static void Main(string[] args)
{
sem.Release(1); //***** This is the sentence ****
for (int i = 0; i < 5; i++)
{
Thread td = new Thread(recordPacking);
td.Name = string.Format(" vehicle {0}", i);
td.Start(td.Name);
}
Console.ReadKey();
} Output is as follows : 
From the above example, we can know that Semaphore The first parameter in the constructor initialCount The real meaning of .
1、 Range : Limited to initialization .
2、Semaphore The number of requests that can be processed at one time
summary
There's a problem with knowing :semaphore and mutex The difference between ?
It's a good story , This involves Mutex And Semaphore The difference between . among “fleuria” The answer is very good , Irrefutable .
边栏推荐
- C#使用WinExec调用exe程序
- 1099 build a binary search tree (30 points)
- 1146 topological order (25 points)
- 2019.10.16 training summary
- Recurrence of vulnerability analysis for Cisco ASA, FTD and hyperflex HX
- 這個開源項目超哇塞,手寫照片在線生成
- September 21, 2020 referer string segmentation boost gateway code organization level
- 逆向思维-小故事
- Power strings [KMP cycle section]
- qgis制图
猜你喜欢

Download control 1 of custom control (downloadview1)

通过Win32API调用另一界面的按钮

The stones game

2021年团体程序设计天梯赛-模拟赛

Nacos registry cluster

2021 team programming ladder competition - Simulation Competition

Codeforces Round #659 (Div. 2)

IIS服务器相关错误

Picture verification code control

SeaweedFS安全配置(Security Configuration)
随机推荐
Voir le classement des blogs pour csdn
Using rancher to build kubernetes cluster
To 3 -- the last programming challenge
SeaweedFS安全配置(Security Configuration)
1021 deep root (25 points)
IIS服务器相关错误
L2-3 这是二叉搜索树吗?-题解超精彩哦
信号作品:时变和时不变
Alibaba cloud firewall configuration, multiple settings (iptables and firewall)
std::unique_ptr<T>与boost::scoped_ptr<T>的特殊性
指针数组、数组指针和传参的相关问题
PGP在加密技术中的应用
Web漏洞手动检测分析
1098 insertion or heap sort (25 points)
2019.10.23 training summary
HDU 4578 transformation (segment tree + skillful lazy tag placement)
Analyze in detail the PBOT mining virus family behavior and the principle of exploited vulnerabilities, and provide detailed protection suggestions for the blue army
Shanke's C language 2018 exercise (Telecom)
Weight recursion of complete binary tree -- the last programming challenge
Codeforces - 1151b thinking