如何在ASP.NET中做异步
先来两个都是延时两秒的方法,需要using System.Threading;using System.Collections.Generic;
{
Label1.Text += "<br>Now: thread1 @ #" + Thread.CurrentThread.GetHashCode();
Thread.Sleep(2000);//延时2秒
}
private void GetData2()
{
Label1.Text += "<br>Now: thread2 @ #" + Thread.CurrentThread.GetHashCode();
Thread.Sleep(2000);//延时2秒
}
{
//直接运行两个延时方法,页面运行大于4秒
GetData(); GetData2();
}
{
//使用委托异步运行两个方法
VoidDelegate vd = GetData;
vd += GetData2;
List<IAsyncResult> il = new List<IAsyncResult>();
foreach (VoidDelegate v in vd.GetInvocationList())
{
il.Add(v.BeginInvoke(null, null));
}
int ii = 0;
foreach (VoidDelegate v in vd.GetInvocationList())
{
v.EndInvoke(il[ii]);//等待方法结束
ii = ii + 1;
}
}
网上大部分的ASP.NET异步代码都是这个的,也只是注册一个异步方法,虽然是给出了实例,但是对比不是很明显:
{
//使用AddOnPreRenderCompleteAsync向Page注册两个异步方法,二次页面回调会出错(?不知道原因)
//另外页面的async也需要设置为true
BeginEventHandler bh = new BeginEventHandler(GetDataAsync);
bh += new BeginEventHandler(GetData2Async);
EndEventHandler eh = new EndEventHandler(EndGetAsyncData);
eh += new EndEventHandler(EndGet2AsyncData);
Page.AddOnPreRenderCompleteAsync(bh, eh);
}
IAsyncResult GetDataAsync(Object src, EventArgs args, AsyncCallback cb, Object state)
{
VoidDelegate vd = GetData;
return vd.BeginInvoke(cb, state);
}
IAsyncResult GetData2Async(Object src, EventArgs args, AsyncCallback cb, Object state)
{
VoidDelegate vd = GetData2;
return vd.BeginInvoke(cb, state);
}
void EndGetAsyncData(IAsyncResult ar) { }
void EndGet2AsyncData(IAsyncResult ar) { }
protected void Button4_Click(object sender, EventArgs e)
{
PageAsyncTask asyncTask1 = new PageAsyncTask(
new BeginEventHandler(GetDataAsync),
new EndEventHandler(EndGetAsyncData),
new EndEventHandler(TimeoutAsyncData),
null, true);//关键:最后一个为true:指示任务能否与其他任务并行处理的值
PageAsyncTask asyncTask2 = new PageAsyncTask(
new BeginEventHandler(GetData2Async),
new EndEventHandler(EndGet2AsyncData),
new EndEventHandler(Timeout2AsyncData),
null, true);
Page.RegisterAsyncTask(asyncTask1);
Page.RegisterAsyncTask(asyncTask2);
Page.ExecuteRegisteredAsyncTasks();
}
void TimeoutAsyncData(IAsyncResult ar) { }
void Timeout2AsyncData(IAsyncResult ar) { }