C#中程序的互斥运行

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()) 语句启动程序;否则显示一个对话框并结束程序运行。

Published At
Categories with Web编程
Tagged with
comments powered by Disqus