C#中Mutex是互斥锁,位于System.Threading 命名空间中。互斥锁是一种互斥的同步对象,意味着同一时间有且仅有一个线程。Mutex适用于一个共享资源每次只能被一个线程访问的情况,也就是控制多个线程相互之间的联系,不产生冲突和重复。
Mutex构造函数,第一个参数决定是否当前线程获取即将创建的Mutex的所有权,第二个参数是互斥变量名(也就是Mutex的名字),第三个是新创建true,还是已存在false。 需要注意的是Mutex对象即使不是新创建的,也需要进行释放,否则下一次获取都是返回已存在
用法: 当Mutex被创建的时候,当前的线程相当于被锁住,如果尝试再打开程序(另一个线程),就会相斥。
要点:Mutex互斥锁一定要程序启动前,线程开始时被使用, 以下是以WPF为例子, 在重写的OnStart()用Mutex失败。
正确的用法:必须重写Main(), 因为Main()是跑在OnStart()前的,而且程序在Main()里面已经启动。
当程序正在运行当中,我们希望界面可以显示已运行的程序,这就需要调用windows的窗体dll
还有其他方法能够实现 方法2
完整代码
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using SingleInstanceApp;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private const string MutexName = "My_Unique_Application_String";
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
}
[STAThread]
public static void Main()
{
bool createNew;
System.Threading.Mutex mutex = new System.Threading.Mutex(true, "test", out createNew);
if (!createNew)
{
MessageBox.Show("The application is running");
ShowToFront("MainWindow");
}
else
{
App app = new App();
app.InitializeComponent();
app.Run();
}
}
[DllImportAttribute("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImportAttribute("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImportAttribute("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public static void ShowToFront(string windowName)
{
IntPtr firstInstance = FindWindow(null, windowName);
ShowWindow(firstInstance, 1);
SetForegroundWindow(firstInstance);
}
}
}