winforms - Could you please explain why this Mutex helping allow to run only 1 instance of application at a time doesn't work (C#)? -
here article read http://kristofverbiest.blogspot.com/2008/11/creating-single-instance-application.html, followed steps article, have following code, i'm sure can't work , can't:
static class program { static mutex mutex; /// <summary> /// main entry point application. /// </summary> [stathread] static void main() { bool alreadyrun; mutex = new mutex(false, guid.newguid().tostring().replace("-", ""), out alreadyrun); if (!alreadyrun) return; application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); application.run(new form1()); } }
the article says mutex name passed in can random, myappname easy debugging (so left out), 'local//' left out. wonder how can work? constructor succeed , turn alreadyrun
true whenever random guid string unique (i mean there hasn't been mutex name created before). means, there little chance alreadyrun
becoming false. in fact, i've tried code above many times , run many instances of application liked.
after trying fixed string "unique" mutex name , works. won't work if there application creating mutex same name. , ended solution:
- we can't use random string, have use fixed string , string should long , complicated, password, id sure there little chance other application use same name. here example i'm sure say, there little chance other (even machine) think of:
ilove.netilovejava1234forever56789thismyid_itisevenlongerlongerlonger_howlongcanitbe_maybe8000characters?_canitbeso?
please explain article (looks pro blogger) , give me other solution using mutex (i've been fed using getprocessesbyname
, it's not far). thanks!
reading article sent not following correctly:
"the name of mutex should contain guid, ensures no other application uses same name. if don’t know how create guid, click here."
not new guid each instance. create guid once making string unique.
you use
static class program { static mutex mutex; /// <summary> /// main entry point application. /// </summary> [stathread] static void main() { var guid = ((system.runtime.interopservices.guidattribute)(system.reflection.assembly.getentryassembly().getcustomattributes(typeof(system.runtime.interopservices.guidattribute), false).single())).value; bool alreadyrun; mutex = new mutex(false, "app_name" + guid.tostring(), out alreadyrun); if (!alreadyrun) return; application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); application.run(new form1()); } }
then if want version of app run @ same time give new guid. can prefix local\ per article if required.
here image
Comments
Post a Comment