Example #1
0
        public static async Task<Ticket> AcquireTicket()
        {
            var count = _tickets.Count;

#if DEBUG
            var totalWaitTime = 0;
#endif

            while (_tickets.Count >= _maxTickets)
            {
                var waitTime = (int)_waitTime + 1;
                
#if DEBUG
                totalWaitTime += waitTime;
#endif

                await Task.Delay(waitTime);
            }

#if DEBUG
            if (totalWaitTime > 0)
            {
                System.Diagnostics.Debug.WriteLine("Had to wait for a ticket for a total of " + totalWaitTime + " ms");
            }
#endif

            Ticket ticket = new Ticket(_index++, DateTime.Now);

            _tickets.Add(ticket);

            return ticket;
        }
Example #2
0
        public static void ReleaseTicket(Ticket ticket)
        {
            var timespan = (long)(DateTime.Now - ticket.Timestamp).TotalMilliseconds;
            var waitTime = (_waitTime + timespan) / 2;
            
#if DEBUG
            System.Diagnostics.Debug.WriteLine("Ticket " + ticket.Id + " was reserved for " + waitTime + " ms");
#endif

            _tickets.Remove(ticket);

            _waitTime = _tickets.Count > 0 ? waitTime : 0;
        }