using System;
using System.Diagnostics;
using System.Threading;
using System.Web.Mvc;
using System.Web.UI;
namespace Portal.Views.Home
{ public partial class Index : ViewPage
{ private string _asyncResult;
private AsyncTaskDelegate _asyncTask;
protected void Page_Load(object sender, EventArgs e)
{ Stopwatch sw = Stopwatch.StartNew();
PageAsyncTask task1 =
new PageAsyncTask(OnTaskBegin, OnTaskEnd, OnTaskTimeout, "A1", true);
PageAsyncTask task2 =
new PageAsyncTask(OnTaskBegin, OnTaskEnd, OnTaskTimeout, "B2", true);
PageAsyncTask task3 =
new PageAsyncTask(OnTaskBegin, OnTaskEnd, OnTaskTimeout, "C3", true);
PageAsyncTask task4 =
new PageAsyncTask(OnTaskBegin, OnTaskEnd, OnTaskTimeout, "D4", true);
RegisterAsyncTask(task1);
RegisterAsyncTask(task2);
RegisterAsyncTask(task3);
RegisterAsyncTask(task4);
// By default, an asynchronous task will time out if it has not completed
// within 45 seconds.
AsyncTimeout = TimeSpan.FromSeconds(60);
ExecuteRegisteredAsyncTasks();
sw.Stop();
// now, we can get the task result here.
Response.Write(_asyncResult);
Response.Write(sw.Elapsed.TotalSeconds);
}
private IAsyncResult OnTaskBegin(object sender,
EventArgs e,
AsyncCallback callback,
object data)
{ _asyncTask = delegate(string text)
{ // TODO: add your async task here.
string response =
string.Format("AsyncTask {0} started at: {1}. ", text, DateTime.Now); Thread.Sleep(TimeSpan.FromSeconds(10));
response +=
string.Format("AsyncTask {0} ended at: {1}.\n", text, DateTime.Now); return response;
};
IAsyncResult result = _asyncTask.BeginInvoke((string) data, callback, data);
return result;
}
private void OnTaskEnd(IAsyncResult ar)
{ _asyncResult += _asyncTask.EndInvoke(ar);
}
private void OnTaskTimeout(IAsyncResult ar)
{ _asyncResult = string.Format("AsyncTask {0} is time out.", ar.AsyncState); }
#region Nested type: AsyncTaskDelegate
protected delegate string AsyncTaskDelegate(string text);
#endregion
}
}