using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyWebApplication.Cache
{
	public partial class DataCache : System.Web.UI.Page
	{
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			MyDataLb.Text = GetData();
		}

		private static string GetData()
		{
			return FetchDataFromDB();
			
			const string cacheKey = "MyData";

			string result = (string)HttpRuntime.Cache[cacheKey];
			if (result == null)
			{
				lock (dataLock)
				{
					result = (string)HttpRuntime.Cache[cacheKey];
					if (result == null)
					{
						result = FetchDataFromDB();

						//HttpRuntime.Cache[cacheKey] = result;
						HttpRuntime.Cache.Add(
							key: cacheKey,
							value: result,
							dependencies: null,
							absoluteExpiration: DateTime.Now.AddSeconds(5),
							slidingExpiration: System.Web.Caching.Cache.NoSlidingExpiration,  // nebo TimeSpan
							priority: System.Web.Caching.CacheItemPriority.Normal,
							onRemoveCallback: null);
					}
				}
			}
			return result;
		}
		private static object dataLock = new object();

		private static string FetchDataFromDB()
		{
			DateTime now = DateTime.Now;
			Thread.Sleep(400);
			//while (true)
			//{
			//	// generujeme zátěž
			//	if (DateTime.Now >= now.AddMilliseconds(400))
			//	{
			//		break;
			//	}
			//}
			return DateTime.Now.ToString();
		}
	}
}