using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace delegatesproject
{
	class Tasks
	{
		public bool Task1(string desc)
		{
			System.Threading.Thread.
				Sleep(5000);
			return true;
		}
		public static bool Task2(string desc)
		{
			System.Threading.Thread.
				Sleep(5000);
			return true;
		}
	}

	delegate bool TaskDel(string desc);

	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class WebForm1 : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button btnSync;
		protected System.Web.UI.WebControls.Button btnAsync;
		protected System.Web.UI.WebControls.Label lblTimeElapsed;
		protected System.Web.UI.WebControls.Label lblTime;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnSync.Click += new System.EventHandler(this.btnSync_Click);
			this.btnAsync.Click += new System.EventHandler(this.btnAsync_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnSync_Click(
			object sender, System.EventArgs e)
		{
			Tasks tsks = new Tasks();
			System.DateTime dt1 = System.DateTime.Now;
			tsks.Task1("Calling Task1...");
			Tasks.Task2("Calling Task2...");
			System.DateTime dt2 = System.DateTime.Now;
			System.TimeSpan tm = dt2 - dt1;
			lblTime.Text = tm.TotalSeconds.ToString();
		}

		private void btnAsync_Click(object sender, System.EventArgs e)
		{
			Tasks tsks = new Tasks();
			TaskDel del1 = new TaskDel(tsks.Task1);
			TaskDel del2 = new TaskDel(Tasks.Task2);
			System.DateTime dt1 = System.DateTime.Now;
			IAsyncResult ar1 = del1.BeginInvoke("Calling Task1...",null,null);
			IAsyncResult ar2 = del2.BeginInvoke("Calling Task2...",null,null);
			System.Threading.WaitHandle[] handles =
				new	System.Threading.WaitHandle[] {ar1.AsyncWaitHandle,ar2.AsyncWaitHandle };
			System.Threading.WaitHandle.WaitAll(handles);
			System.DateTime dt2 = System.DateTime.Now;
			System.TimeSpan tm = dt2 - dt1;
			lblTime.Text =	tm.TotalSeconds.ToString();
		}
	}
}
