Encapsulate a lock processing class and a lock processing class
During development, to prevent multiple threads from accessing the same resource at the same time, we usually perform lock processing. However, it is not very nice to see the scattered lock code written by some colleagues, therefore, encapsulate the following:
No title
Internal struct TimedLock: IDisposable {// <summary> // default timeout seconds /// </summary> private const int timeoutSeconds = 5; /// <summary> /// lock the object /// </summary> private object target; /// <summary> /// throws an exception upon timeout /// </summary> private static bool throwTimeoutException; /// <summary> /// constructor /// </summary> /// <param name = "o"> </param> private TimedLock (object o) {target = o ;}/// <summary> // lock the object /// </Summary> /// <param name = "o"> object to be locked </param> /// <param name = "timeout"> timeout settings, the default value is int. maxValue </param> /// <param name = "throwException"> throws an exception upon timeout </param> /// <returns> </returns> public static TimedLock Lock (object o, timeSpan? Timeout = null, bool throwException = false) {if (timeout = null) {timeout = TimeSpan. fromSeconds (timeoutSeconds);} throwTimeoutException = throwException; return GetLock (o, timeout. value );} /// <summary> /// obtain the lock /// </summary> /// <param name = "o"> object to be locked </param> /// <param name = "timeout"> timeout settings </param> // <returns> </returns> private static TimedLock GetLock (object o, timeSpan timeout) {Timed Lock tl = new TimedLock (o); if (! Monitor. tryEnter (o, timeout) & throwTimeoutException) {throw new TimeoutException ("Timeout waiting for lock");} Console. writeLine ("Entered Thread" + Thread. currentThread. getHashCode () + ":" + DateTime. now); return tl ;}//< summary> /// destroy and release the lock /// </summary> public void Dispose () {if (target! = Null) Monitor. Exit (target) ;}} call example: class Program
{
Private static object o = new object ();
Static void Main (string [] args)
{
// Retry ();
Var t1 = new Thread (new ThreadStart (LockedSample1 ));
T1.Name = "t1 ";
T1.Start ();
Var t2 = new Thread (new ThreadStart (LockedSample1 ));
T2.Name = "t2 ";
T2.Start ();
Console. ReadKey ();
}
Static void LockedSample1 ()
{
Using (TimedLock lo = TimedLock. Lock (o, TimeSpan. FromSeconds (5), true ))
{
LockedSample2 ();
}
}
Static void LockedSample2 ()
{
System. Threading. Thread. Sleep (10000 );
}
}