I've looked through SO for this issue, but the other instances seem to relate only to multi-threaded app issues.
My app is a straightforward single-form, single-thread app and I'm just using a mutex to ensure only one instance is run on the host system.
Here is my code:
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();
}
}
}
}
It fails on the ReleaseMutex() call with the error Object synchronization method was called from an unsynchronized block of code.
Can someone explain what I'm doing wrong? The mutex was originally a static variable, but putting it inside the Main() function didn't stop the error occurring.