c# - Process mutex on function -


how can lock function such blocks other instances of program executing until it's finished?

i think need system mutex of kind , waitone i'm not sure how put in robust way. i'm thinking like...

public static void function() {     bool ok;      using (mutex mutex = new mutex(true, "set-ip instance", out ok))     {         if(!ok)         {                                 mutex.waitone();         }          ...     } }   

the behavior looking can achieved code (simple version):

using(mutex mutex = new mutex(false, "globalmutexid")) {     mutex.waitone();     //do thing     mutex.releasemutex(); } 

or if prefer more reusable approach:

public class mutexfactory {     private string _name;      public mutexfactory(string name)     {         _name = name;     }      public singleusemutex lock()     {         return new singleusemutex(_name);     } }  public class singleusemutex : idisposable {     private readonly mutex _mutex;      internal singleusemutex(string name)     {         _mutex = new mutex(false, name);         _mutex.waitone();     }      public void dispose()     {         _mutex.releasemutex();         _mutex.dispose();     } } 

can used this:

private void testfunction() {     mutexfactory factory = new mutexfactory("yourmutexid");      (int = 0; < 100; i++)     {         // works new instances of program of course         new thread(interlocked).start(factory);     } }  private void interlocked(object obj) {     guid guid = guid.newguid();     mutexfactory factory = obj mutexfactory;     using (factory.lock())     {         debug.writeline(guid.tostring("n") + " start");         //waste time         thread.sleep(50);         debug.writeline(guid.tostring("n") + " end");        } } 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -