c# - Avoid from running more than one instance -


i'm trying set mutex in order allow running application in 1 instance only. wrote next code (like suggested here in other post)

 public partial class app : application     {          private static string appguid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";          protected override void onstartup(startupeventargs e)         {             using (mutex mutex = new mutex(false, "global\\" + appguid))             {                  if (!mutex.waitone(0, false))                 {                     messagebox.show("instance running");                     return;                 }                  base.onstartup(e);                 //run application code             }         }      } 

regretfully code isn't working. can launch application in multiple instances. has idea wrong in code? thanks

you disposing mutex after running first instance of application. store in field instead , don't use using block:

public partial class app : application {     private mutex _mutex;     private static string appguid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";      protected override void onstartup(startupeventargs e)     {         bool creatednew;         // thread should own mutex, pass true         _mutex = new mutex(true, "global\\" + appguid, out creatednew);         if (!creatednew)         {             _mutex = null;             messagebox.show("instance running");             application.current.shutdown(); // close application!             return;         }          base.onstartup(e);         //run application code     }      protected override void onexit(exiteventargs e)     {                   if(_mutex != null)             _mutex.releasemutex();         base.onexit(e);     } } 

output parameter creatednew returns false if mutex exist.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -