惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
罗磊的独立博客
腾讯CDC
云风的 BLOG
云风的 BLOG
月光博客
月光博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
U
Unit 42
I
InfoQ
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
美团技术团队
IT之家
IT之家
Stack Overflow Blog
Stack Overflow Blog
F
Fortinet All Blogs
GbyAI
GbyAI
S
SegmentFault 最新的问题

博客园 - rottenapple

我遇到的Sqlserver2005 SSIS 的Bug SSIS导入Oracle中的性能问题 Excel内容不能正确倒入SSIS? 使用Oracle Generic Connectivity连接SqlServer asp.net下的用户权限管理模块设计 msdn也出现这种错误。。。 为Log4Net添加异常处理模块 - rottenapple - 博客园 ibatis.net的配置文件设计 今天发现了ibatis.net的一个bug The Visual Studio template information is out of date. asp.net 设计中的页面流程控制的一点想法(讨论贴) - rottenapple - 博客园 New job,New chance 使用强类型DataSet的好处 在Framework1.0下同时连接SqlServer和Oracle的一些体会 VS2002 与 IIS6.0的一个bug 利用WSDL2JAVA实现JAVA调用.Net的Web Services(1) T_SQL中的事务处理 SqlCommand的ExecuteNonQuery()方法执行多条T-SQL语句 博客园的Bug
如何使应用程序只有一个实例在运行
rottenapple · 2005-08-05 · via 博客园 - rottenapple

上网搜索了一下,发现大家都提到了一个方法,使用Mutex类,但是其中有个问题很多人没有遇到。
就是如果项目文件很大的话,Mutex 对象在编译的时候可能会被当成垃圾给释放掉。
[STAThread]
    static void Main()                  // args are OK here, of course
    {
        bool ok;
        m = new System.Threading.Mutex(true, "YourNameHere", out ok);

        if (! ok)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }

        Application.Run(new Form1());   // or whatever was there

        GC.KeepAlive(m);                // important!
    }

其中GC.KeepAlive()必须有,原因如下:
We want the program to keep hold of the mutex as long as it's running. But the JIT compiler sees that the mutex is only used near the beginning of the program, and may discard it prematurely when memory is needed for something else!