您的位置:首页 > 其它

创建单例winform应用程序的一种更好的方式

2011-05-04 06:09 134 查看
我们经常会创建一些单例winform应用程,但如何保证单例,最常用的方法就是扫描进程,但这种方式缺点是显而易见的,这里介绍一种方式。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Reflection;

static class Program
{
private static Mutex singleton;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
bool   has=Check() ;
if (has)
{
Form form = new Form1();
form.FormClosed += new FormClosedEventHandler(form_FormClosed);
Application.Run(form);
}
else {
MessageBox.Show("已启动");

}
}

static void form_FormClosed(object sender, FormClosedEventArgs e)
{
if (singleton != null) {
singleton.Close();
}
}
private static bool Check() {
bool   has=false;
singleton=new   Mutex(false,Assembly.GetExecutingAssembly().FullName,out has);
//   Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
return has;
}
}
}

注意点:

1使用Mutex类,设置一个静态命名的实例

如:private static Mutex singleton;

注意名称是Assembly.GetExecutingAssembly().FullName,为程序入口程序集的名字

注意

在运行终端服务的服务器上,已命名的系统 mutex 可以具有两级可见性。 如果名称以前缀“Global\”开头,则 mutex 在所有终端服务器会话中均为可见。 如果名称以前缀“Local\”开头,则 mutex 仅在创建它的终端服务器会话中可见。 在这种情况下,服务器上各个其他终端服务器会话中都可以拥有一个名称相同的独立 mutex。 如果创建已命名 mutex 时不指定前缀,则它将采用前缀“Local\”。 在终端服务器会话中,只是名称前缀不同的两个 mutex 是独立的 mutex,这两个 mutex 对于终端服务器会话中的所有进程均为可见。 即:前缀名称“Global\”和“Local\”说明 mutex 名称相对于终端服务器会话(而并非相对于进程)的范围。

微软说明
2通过创建Mutex的实例来判断程序是否已启动。

private static bool Check() {
bool   has=false;
singleton=new   Mutex(false,Assembly.GetExecutingAssembly().FullName,out has);
//   Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
return has;
}

3在程序关闭时,关闭Mutex的实例

form.FormClosed += new FormClosedEventHandler(form_FormClosed);

static void form_FormClosed(object sender, FormClosedEventArgs e)
{
if (singleton != null) {
singleton.Close();
}
}


作者:xuexiaodong2009 发表于2011-5-4 14:09:00 原文链接

阅读:48 评论:0 查看评论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: