我已经经历了这么看了这个问题,但其他实例似乎只涉及到多线程应用程序的问题。ReleaseMutex在单线程的C#Windows失败窗体应用程序
我的应用程序是一个简单单的形式,单线程应用程序,我只是用一个互斥体,以确保只有一个实例在主机系统上运行。
这是我的代码:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace UPGRADE
{
static class Program
{
[STAThread]
static void Main()
{
Mutex mSpartacus;
Assembly myAssembly = Assembly.GetExecutingAssembly();
GuidAttribute ga = (GuidAttribute)myAssembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0);
string sMyGUID = ga.Value.ToString().ToUpper();
string sMutexId = @"Global\{" + sMyGUID + @"}";
bool bMutexAcquired = false;
mSpartacus = new Mutex(false, sMutexId, out bMutexAcquired);
if (!bMutexAcquired)
{
MessageBox.Show("Upgrade.exe is already running.\n\nOnly one instance can run at once.", "Already running");
return;
}
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myForm = new Form1();
Application.Run(myForm);
}
finally
{
mSpartacus.ReleaseMutex();
}
}
}
}
它未能在ReleaseMutex()与误差对象同步方法是从代码不同步块称为调用。
有人可以解释我做错了什么吗?互斥体最初是一个静态变量,但将它放入Main()函数内并不能阻止发生错误。
非常感谢吉荣 - 解决了它。 – intDattashame
我在SO上读过关于它的最佳解释 –