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
Post a Comment