为什么以下使用 PageAsyncTask 的 ASP.NET 代码执行总计 8 秒,无论我按原样运行还是使用 PageAsyncTask 注释 2 行并取消 Page_load 中的 Thread.Sleep(5000) 注释?:
//PageAsyncTask asyncTask1 = new PageAsyncTask(BeginAsyncOperation,
EndAsyncOperation,<br/>
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/>");
}
}
最佳答案
这是因为您实际上并未并行运行任何内容 - 所有 PageAsyncTask
均在 ExecuteRegisteredAsyncTasks()
页面方法调用上运行,并且Page_PreRender
结束后立即自动发生(并且 Page_PreRenderComplete
在所有任务完成或超时后启动):http://msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx
Any asynchronous tasks registered before the PreRenderComplete event will be executed automatically by the page if they have not already been executed. Those asynchronous tasks registered after the PreRenderComplete event must be executed explicitly through the ExecuteRegisteredAsyncTasks method. The ExecuteRegisteredAsyncTasks method can also be used to start tasks before the PreRenderComplete event. The ExecuteRegisteredAsyncTasks method executes all the registered asynchronous tasks on the page that have not been executed.
因此,您必须在任何 Thread.Sleep() 之前在
开始。或者将每个 Page_Load
中手动调用 ExecuteRegisteredAsyncTasks()
(可以安全地调用任意次数) Thread.Sleep()
放在不同的 PageAsyncTask
中 - 但确保第五个参数(用于并行执行)为 true
,并且设置页面异步指令:<%@ Page Async="true"%>
关于c# - PageAsyncTask 时间与顺序进程相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9075674/