C#中程序的互斥运行

来源:互联网 发布:云优化 编辑:程序博客网 时间:2024/05/22 12:05
Using System;
Using System.Drawing;
Using System.Collections;
Using System.ComponentModel;
Using System.Windows.Forms;
Using System.Data;
Using System.Threading;
namespace exam_使用程序只能够运行一个
{
pulic class Forms:System.Windows.Forms.Form
{
   [STAThread]
   static void Main()
     {
     bool createdNew;
      Mutex m=new Mutext(true,”test”,out createdNew);
            if (createdNew)
              {
Application.Run(new Form1());
m.ReleaseMutex();
             }
          else
             {
Messagebox.Show(“本程序只允许同时运行一个”);
             }
     }
 }
}
程序通过Mutex m=new Mutext(true,”test”,out createdNew);语句创建一个互斥体变量m,其中true参数表示调用线程拥有互斥体的初始所属权,test为互斥体名,并且将调用线程是否已被授权互斥体的初始所属权的布尔值保存在createdNew变量中。然后通过判断该变量值决定是否启动本程序,如果为true,则无正在运行的本实例,通过Application.Run(new Form1())语句启动程序;否则显示一个对话框并结束程序运行。