Listing 1: C# • Use Lazy Evaluation

If a property value doesn't change often, you can use lazy evaluation to compute the value when it is first accessed. However, you must be careful to reset the value when a change occurs and to ensure that you have proper locking around the code that changes the value and the code that performs the initial calculation.

public sealed class NumericSequence
{
	private List<int> numberSequence = new List<int>();

	public NumericSequence()
	{
	}

	private object syncHandle;

	private object GetSynchHandle()
	{
		System.Threading.Interlocked.CompareExchange(
			ref syncHandle, new object(), null);
		return syncHandle;
	}

	public NumericSequence(IEnumerable<int> seeds)
	{
		foreach (int i in seeds)
			numberSequence.Add(i);
	}

	public void AddToSequence(int num)
	{
		lock (GetSynchHandle())
		{
			numberSequence.Add(num);
			sum = default(int?);
		}
	}

	public void AddToSequence(
		IEnumerable<int> moreNumbers)
	{
		lock (GetSynchHandle())
		{
			numberSequence.AddRange(moreNumbers);
			sum = default(int?);
		}
	}

	private int? sum;
	public int Sum
	{
		get
		{
			lock (GetSynchHandle())
			{
				if (sum.HasValue == false)
				{
					sum = 0;
					numberSequence.ForEach(delegate(int 
						num)
					{
						sum += num;
					});
				}
				return sum.Value;
			}
		}
	}
}
comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.