从这里,我找到了一个 javascript 事件队列,可以帮助我做我想做的事:
<script type="text/javascript">
Sys.Application.add_load(ApplicationLoadHandler)
function ApplicationLoadHandler(sender, args) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack()) {
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(CompleteRequest);
}
}
var myQueue = new Array();
function InitializeRequest(sender, args) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack()) {// if it's working on another request, cache the current item that cause the request
args.set_cancel(true);
Array.add(myQueue, args.get_postBackElement());
}
}
function CompleteRequest(sender, args) {
if (myQueue.length > 0) {// fire corresponding event again of the item cached
$get(myQueue[0].id).click();
Array.removeAt(myQueue, 0);
}
}
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
</script>
这也可以从代码隐藏中呈现,如下所示:
StringBuilder script = new StringBuilder();
script.Append("Sys.Application.add_load(ApplicationLoadHandler)\n");
script.Append("function ApplicationLoadHandler(sender, args) {\n");
script.Append(" var prm = Sys.WebForms.PageRequestManager.getInstance();\n");
script.Append(" if (!prm.get_isInAsyncPostBack()) {\n");
script.Append(" prm.add_initializeRequest(InitializeRequest);\n");
script.Append(" prm.add_endRequest(CompleteRequest);\n");
script.Append(" }\n");
script.Append("}\n");
script.Append("var myQueue = new Array();\n");
script.Append("function InitializeRequest(sender, args) {\n");
script.Append(" var prm = Sys.WebForms.PageRequestManager.getInstance();\n");
script.Append(" if (prm.get_isInAsyncPostBack()) {\n");
script.Append(" args.set_cancel(true);\n");
script.Append(" Array.add(myQueue, args.get_postBackElement());\n");
script.Append(" }\n");
script.Append("}\n");
script.Append("function CompleteRequest(sender, args) {\n");
script.Append(" if (myQueue.length > 0) {\n");
script.Append(" $get(myQueue[0].id).click();\n");
script.Append(" Array.removeAt(myQueue, 0);\n");
script.Append(" }\n");
script.Append("}\n");
script.Append("if (typeof (Sys) !== \"undefined\") Sys.Application.notifyScriptLoaded();");
ClientScript.RegisterStartupScript(this.GetType(), "EventQueue", script.ToString(), true);
不管添加这个队列脚本的方法是什么,我发现我需要给按钮点击添加一点延迟才能让它们排队:
ClientScript.RegisterStartupScript(this.GetType(), "RefreshGridA", "setTimeout(\"document.getElementById('" + btnRefreshGridA.ClientID + "').click();\",100);", true);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshGridB", "setTimeout(\"document.getElementById('" + btnRefreshGridB.ClientID + "').click();\",100);", true);
如果没有 setTimeout,只有最后一个按钮会像以前一样完成刷新。
从根本上说,刷新调用实际上并不是多线程的;它们是连续执行的。但是,我现在对用户体验感到满意。