Skip to content

Instantly share code, notes, and snippets.

@rushfrisby
Created June 30, 2015 15:41
Show Gist options
  • Save rushfrisby/fbf20351986b2d553e9e to your computer and use it in GitHub Desktop.
Save rushfrisby/fbf20351986b2d553e9e to your computer and use it in GitHub Desktop.
Using KeyLocker
class KeyLockerExample
{
static readonly ThreadState[] StopStates = { ThreadState.AbortRequested, ThreadState.Aborted };
static void Main()
{
var threads = new List<Thread>();
var sw = new Stopwatch();
var timelimit = new TimeSpan(0, 0, 30);
threads.Add(new Thread(x => DoLocking(1)));
threads.Add(new Thread(x => DoLocking(2)));
threads.Add(new Thread(x => DoLocking(3)));
sw.Start();
threads.ForEach(x => x.Start());
while (sw.Elapsed < timelimit)
{
Thread.Sleep(100);
}
threads.ForEach(x => x.Abort());
Console.WriteLine("Done!");
Console.ReadKey();
}
static void DoLocking(int threadId)
{
var r = new Random(threadId);
while (!StopStates.Contains(Thread.CurrentThread.ThreadState))
{
var i = r.Next(1, 3);
using (new KeyLocker(i))
{
Console.WriteLine("Thread " + threadId + " Locked " + i + " at " + DateTime.Now);
Thread.Sleep(2000);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment