C#

同步资源调用

private System.Threading.Mutex mut = new System.Threading.Mutex();
// Wait until it is safe to enter, and do not enter if the request times out.
if (mut.WaitOne(1000)) {

    // access non-reentrant resources here.

    // Release the Mutex.
    mut.ReleaseMutex();
}
else {
    return;
}

软件单例运行

private System.Threading.Mutex mut;
bool isCreated;
// 第二个参数 互斥体名称
// 第三个参数 如果存在指定名称的互斥体,则不创建该互斥体,并返回false;否则创建该互斥体并返回true
// 第一个参数 true时,将创建的(第一个参数)指定名称的(第二个参数)互斥体授权给调用的线程
mut = new System.Threading.Mutex(true, "MyAppName", out isCreated);
// false时,表示进程中存在同名的互斥体,即我们已经运行了一个软件实例,所以退出当前软件
if (!isCreated)
{
    MessageBox.Show("已有一个程序实例运行");
    Environment.Exit(0);
}

参考

Mutex Class (System.Threading) | Microsoft Docs

原文地址:https://www.cnblogs.com/zdfffg/p/12611854.html