Single instance application not starting
I developed a single instance WinForm application using .net 4.5 and a mutex on the Main class. Some user report that they can't start the application because the mutex is already taken.
static string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value + "-OrientalWave";
public static string GUID { get { return guid; } }
[STAThread]
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
// Single Instance Check
bool createdNew;
using (var mutex = new Mutex(true, guid, out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0)
{
string filename = args[0];
Application.Run(new frmMain(filename));
}
else
Application.Run(new frmMain());
}
else
{
if (args.Length > 0)
{
// If i want to open a file
string filename = args[0];
NamedPipesClient pipeClient = new NamedPipesClient();
pipeClient.Start();
pipeClient.SendMessage(filename);
pipeClient.Stop();
}
else
MessageBox.Show("Only single instance allowed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
try
{
var exception = (Exception)args.ExceptionObject;
MessageBox.Show(exception.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
Logger.Write(Logger.LogType.Error, exception.Source, "Message: " + exception.Message + " - Stack: " + exception.StackTrace);
}
catch { }
Environment.Exit(0);
}
I searched the web for a solution or an alternative way to create a single instance application but with no success.
It can happen if there is any abandoned mutex. You should catch AbandonedMutexException and release the mutex by calling ReleaseMutex(); Then you should be able to acquire a mutex.
You can find a similar use case here http://gonetdotnet.blogspot.in/2017/08/solved-how-to-handle-log4net.html
链接地址: http://www.djcxy.com/p/51176.html下一篇: 单实例应用程序无法启动