multithreading - Best way to implement lock in C# -
i have object used access sql server table, insert / updates.
i have 2 windows services, use same object read/write same table.
to preserve integrity, using mutex lock , release on object. of late getting sync errors (object synchronization method called unsynchronized block of code). hence adding bool identify caller (in code below bool isthreadownedlockaskingtorelease in 'release' method). resolve sync issues , correct way?
class st
public st() //constructor { mutex stbusy = utils.getmutex(@"st"); bool lockacquired = false; lock (ex) { //open connection // build dataset // close conn } } // ... public bool lock(string nameoflock) { if (stbusy != null) { if (stbusy.waitone(2000)) { lockacquired = true; //... } } return lockacquired; } public void release(string nameofunlocker, bool isthreadownedlockaskingtorelease) { if (stbusy != null && isthreadownedlockaskingtorelease) { stbusy.releasemutex(); } }
class service1:
st st; bool smlock = st.lock("stlock"); if (smlock) { st = new st(); // construct object // work st.release("stlock",smlock); // 2nd param added identify locker }
class service2:
st st1; bool lockowner = st1.lock("qm"); st1= new statustable(); //do work // unlock status table st1.release("qm", lockowner); // addl. parameter added fix sync issue
Comments
Post a Comment