Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- new Thread(FastClient1_OnId1).Start();
- new Thread(FastClient2_OnId1).Start();
- new Thread(SlowClient1_OnId2).Start();
- Console.ReadKey();
- }
- /// <summary>
- /// Long running from the beginning
- /// </summary>
- static void SlowClient1_OnId2()
- {
- Thread.Sleep(500); // allow a fast thread to start ...
- ConcurrencyEmergencyManager.RequestAndWaitForEmergencyGrant(2);
- Console.WriteLine("{0} Slow client works on id 2", DateTime.Now);
- Thread.Sleep(15000);
- Console.WriteLine("{0} Slow client finsihed on id 2", DateTime.Now);
- ConcurrencyEmergencyManager.ReleaseGrantForEmergency(2);
- }
- static void FastClient1_OnId1()
- {
- for (int i = 0; i < 4; i++)
- {
- ConcurrencyEmergencyManager.RequestAndWaitForEmergencyGrant(1);
- Console.WriteLine("{0} Client 1 works on id 1", DateTime.Now);
- Thread.Sleep(2000);
- ConcurrencyEmergencyManager.ReleaseGrantForEmergency(1);
- }
- }
- static void FastClient2_OnId1()
- {
- for (int i = 0; i < 4; i++)
- {
- ConcurrencyEmergencyManager.RequestAndWaitForEmergencyGrant(1);
- Console.WriteLine("{0} Client 2 works on id 1", DateTime.Now);
- Thread.Sleep(2500);
- ConcurrencyEmergencyManager.ReleaseGrantForEmergency(1);
- }
- }
- }
- public static class ConcurrencyEmergencyManager
- {
- private static object _syncRootGrant = new object();
- private static List<int> _emergenciesCurrentInUseList = new List<int>();
- public static void RequestAndWaitForEmergencyGrant(int emergencyId)
- {
- lock (_syncRootGrant)
- {
- while (_emergenciesCurrentInUseList.Where(i => i == emergencyId).Count() != 0)
- {
- Monitor.Wait(_syncRootGrant);
- }
- _emergenciesCurrentInUseList.Add(emergencyId);
- }
- }
- public static void ReleaseGrantForEmergency(int emergencyId)
- {
- lock (_syncRootGrant)
- {
- _emergenciesCurrentInUseList.Remove(emergencyId);
- Monitor.PulseAll(_syncRootGrant);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement