Here is the sample code for achieving asynchronous calls in ASP.NET using IAsyncResult
Asynchronous Provider:
public delegate List<Test> AsyncMethodCaller();
public class AsyncProvider
{
public List<Test> GetTests()
{
System.Threading.Thread.Sleep(2000);
return TestServices.provider.GetAllTests();
}
}
public class AsyncProvider
{
public List<Test> GetTests()
{
System.Threading.Thread.Sleep(2000);
return TestServices.provider.GetAllTests();
}
}
Using BeginInvoke and EndInvoke along with IAsyncResult in .aspx page:
public partial class TestAsync : System.Web.UI.Page
{
IAsyncResult result = default(IAsyncResult);
AsyncProvider _provider = new AsyncProvider();
AsyncMethodCaller caller = default(AsyncMethodCaller);
List<Test> res = default(List<Test>);
protected void Page_Load(object sender, EventArgs e)
{
txtFirstLoad.Text = "loaded first";
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
caller = new AsyncMethodCaller(_provider.GetTests);
}
protected override void CreateChildControls()
{
base.CreateChildControls();
result = caller.BeginInvoke(null, null);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
res = caller.EndInvoke(result);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
grid.DataSource = res;
grid.DataBind();
grid.RenderControl(writer);
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
}
{
IAsyncResult result = default(IAsyncResult);
AsyncProvider _provider = new AsyncProvider();
AsyncMethodCaller caller = default(AsyncMethodCaller);
List<Test> res = default(List<Test>);
protected void Page_Load(object sender, EventArgs e)
{
txtFirstLoad.Text = "loaded first";
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
caller = new AsyncMethodCaller(_provider.GetTests);
}
protected override void CreateChildControls()
{
base.CreateChildControls();
result = caller.BeginInvoke(null, null);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
res = caller.EndInvoke(result);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
grid.DataSource = res;
grid.DataBind();
grid.RenderControl(writer);
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
}
No comments:
Post a Comment