为什么使用PageAsyncTask的以下ASP.NET代码总共执行8秒,无论我是按原样运行还是使用PageAsyncTask注释2行并在Page_load中取消注释Thread.Sleep(5000)?:
//PageAsyncTask asyncTask1 = new PageAsyncTask(BeginAsyncOperation,
EndAsyncOperation,
OperationTimeOut, arr, true);
//Page.RegisterAsyncTask(asyncTask1);
Thread.Sleep(5000);
我知道PageAsyncTask与其他任务并行运行任务,在这种情况下应该使页面加载的整个过程更快。我错过了什么?
public partial class _Default : System.Web.UI.Page
{
public delegate string foo(string param1, string param2);
public IAsyncResult BeginLongRunningTransaction(AsyncCallback cb, object state)
{
var arr = (string[])state;
string z1 = arr[0];
string z2 = arr[1];
foo method = this.LongRunningTransaction;
return method.BeginInvoke(z1, z2, cb, state);
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString() + "<br/>");
string[] arr = { "Zorik1", "Zorik2" };
// if I comment following two lines and un-comment
// Thread.Sleep(5000) command the process runs 8 sec. regardless
PageAsyncTask asyncTask1 = new PageAsyncTask(BeginAsyncOperation, EndAsyncOperation, OperationTimeOut, arr, true);
Page.RegisterAsyncTask(asyncTask1);
//Thread.Sleep(5000);
Thread.Sleep(1000);
Thread.Sleep(1000);
Thread.Sleep(1000);
}
private IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
AsyncCallback cb, object state)
{
return this.BeginLongRunningTransaction(cb, state);
}
private string LongRunningTransaction(string param1, string param2)
{
Thread.Sleep(5000);
txtAsync.Text = "Updated";
updPnl1.Update();
return "this is return string";
}
private void EndAsyncOperation(IAsyncResult ar)
{
}
private void OperationTimeOut(IAsyncResult asyncResult)
{
string a = "";
}
protected void Page_PreRender(object s, EventArgs e)
{
string a = "";
Response.Write(DateTime.Now.ToString() + "<br/>");
}
protected void Page_PreRenderComplete(object s, EventArgs e)
{
Response.Write(DateTime.Now.ToString() + "<br/>");
}
}
答案 0 :(得分:3)
那是因为你实际上没有并行运行任何内容 - 所有PageAsyncTask
都在ExecuteRegisteredAsyncTasks()
页面方法调用上运行,并且会在{{1}之后自动发生} ends(和Page_PreRender
在所有任务完成或超时后启动):http://msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx
如果尚未执行PreRenderComplete事件之前注册的任何异步任务将由页面自动执行。必须通过ExecuteRegisteredAsyncTasks方法显式执行在PreRenderComplete事件之后注册的那些异步任务。 ExecuteRegisteredAsyncTasks方法还可用于在PreRenderComplete事件之前启动任务。 ExecuteRegisteredAsyncTasks方法执行页面上尚未执行的所有已注册异步任务。
因此,在任何Page_PreRenderComplete
开始之前,您必须在ExecuteRegisteredAsyncTasks()
中手动呼叫Page_Load
(可以安全地多次呼叫)。或者将每个Thread.Sleep()
放在不同的Thread.Sleep()
中 - 但要确保第五个参数(用于并行执行)是PageAsyncTask
,并设置该页面async指令:&lt;%@ Page Async = “true”%&gt;