Click here to Skip to main content
15,892,697 members
Articles / Programming Languages / C#

Event traffic calming

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
26 Jan 2013CPOL6 min read 17K   207   6  
How to build an object to calm down event traffic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using NLipsum.Core;

namespace SampleDomain
{
	public class OrderRepository : IOrderRepository
	{
		private const int Capacity = 100;
		private const int RemoveWhenFull = 50;

		private readonly Random _randomPause = new Random();
		private readonly List<Order> _orders = new List<Order>();
		private readonly LipsumGenerator _lipsum = new LipsumGenerator(Lipsums.LoremIpsum, false);

		private bool _generating;

		public void StartGenerating()
		{
			_generating = true;

			Action generateAsynchronously = () => GenerateOrders();
			generateAsynchronously.BeginInvoke(null, null);
		}

		private void GenerateOrders()
		{
			while (_generating) {
				var order = GenerateOrder();
				PutOrderIn(order);

				OnOrderArrived(EventArgs.Empty);
				SleepRandomTime();
			}
		}

		private Order GenerateOrder()
		{
			return new Order {
				CreatedAt = DateTime.Now,
				Title = _lipsum.GenerateSentences(1)[0]
			};
		}

		private void PutOrderIn(Order order)
		{
			if (_orders.Count == Capacity)
				RemoveFromFront();

			_orders.Add(order);
		}

		private void RemoveFromFront()
		{
			_orders.RemoveRange(0, RemoveWhenFull);
		}

		private void SleepRandomTime()
		{
			var time = _randomPause.Next(0, 10);
			Thread.Sleep(time);
		}

		public void StopGenerating()
		{
			_generating = false;
		}

		public IEnumerable<Order> ListFrom(DateTime startDate)
		{
			return _orders.Where(x => x.CreatedAt >= startDate);
		}

		public event EventHandler OrderArrived;

		private void OnOrderArrived(EventArgs e)
		{
			if (OrderArrived != null)
				OrderArrived(this, e);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect SunHotels
Spain Spain
I Received a Bachelor's Degree in Computer Science at the Mathematics and Computer Science Faculty, University of Havana, Cuba.

I mainly work in web applications using C# and some Javascript. Some very few times do some Java.

Comments and Discussions