您可以在这里快速查找:


 
您的位置: 编程学习 > asp.net教程 > 200602
文章分类

Java技术
2005: 03 04 05 06 07 08
09 10 11 12
2006: 01 02

Asp.net
2005: 07 08 09 10 11 12
2006: 01 02

VB编程
2006: 02

Asp编程
2005: 11 12
2006: 01 02

C++/VC
2005: 10 11 12
2006: 01 02

Delphi
2005: 12
2006: 01 02

其它

 本文章适合所有读者

使应用程序只能运行单个实例。

greystar

以前在VB中要防止应用程序运行多个实例的方式很简单,判断APP.PrevInstance 就可以了。

来看一下.NET中是如何实现的,主要使用Mutex来实现进程间同步

using System;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace LogisticsSystem
{
 /// <summary>
 /// 使应用程序只能运行一个实例 的摘要说明。
 /// </summary>
 public class AppSingleton
 {
  static Mutex m_Mutex;

  public static void Run()
  {
   if(IsFirstInstance())
   {
    Application.ApplicationExit += new EventHandler(OnExit);
    Application.Run();
   }
   
  }
  public static void Run(ApplicationContext context)
  {
   if(IsFirstInstance())
   {
    Application.ApplicationExit += new EventHandler(OnExit);
    Application.Run(context);
   }
  }
  public static void Run(Form mainForm)
  {
   if(IsFirstInstance())
   {
    
    Application.ApplicationExit += new EventHandler(OnExit);
   
    Application.Run(mainForm);

   
   }
   else
   {
    
    MessageBox.Show("应用程序已启动,请在任务管理中关闭后再启动!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
   }
  }
  static bool IsFirstInstance()
  {
   m_Mutex = new Mutex(false,"SingletonApp Mutext");
   bool owned = false;
   owned = m_Mutex.WaitOne(TimeSpan.Zero,false);
   return owned ;
  }
  static void OnExit(object sender,EventArgs args)
  {
   m_Mutex.ReleaseMutex();
   m_Mutex.Close();
  }
 }
}

具体使用是如下

using System;
using System.Drawing;
using System.Windows.Forms;
namespace LogisticsSystem
{
 /// <summary>
 /// MainClass 的摘要说明。
 /// </summary>
 public class MainClass
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   
   
   AppSingleton.Run(new mainForm());
   //Application.Run(new mainForm());
  }
 }
}