在我的表单中有一个“提交按钮”和另一个计时器...提交按钮提交一个可能需要几分钟才能服务的请求..意思是计时器会以很短的时间间隔(比如 5 秒)轮询并保持用户已更新。但问题是,一旦单击“提交”按钮,计时器就会停止轮询。我附上了应用程序的工作示例代码。有人知道为什么会这样吗。提前致谢。
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Submit_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer ID="Timer1" Interval="700" runat="server" OnTick="UpdateTimer_Tick">
</asp:Timer>
</form>
</body>
代码隐藏
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
Debug.Write("Timer");
Label1.Text = DateTime.Now.ToString();
}
protected void Submit_Click(object sender, EventArgs e)
{
Debug.Write("Submit Start ");
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(100);
}
Debug.Write("Submit End ");
}
最佳答案
我认为计时器在回发时停止(单击按钮),只有在回发返回时才会重新开始。一种解决方案是使用 PageMethods 而不是计时器,但您只能将静态函数设为 PageMethod。例如,它将像这样工作:
[WebMethod()] public static string GetTime(){
Return DateTime.Now.ToString();
}
html 和 javascript (jquery):
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Submit_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<script type="text/javascript">
function OnSuccess(result, ctrl) { $('#<%=Label1.ClientID %>').html(result); }
function OnError() { alert("error!"); }
$(document).ready(function() {
setInterval(function() { PageMethods.GetTime(OnSuccess, OnError); }, 700)
});
</script>
</form>
</body>
使用网络方法时不要忘记设置 EnablePageMethods="true"!
测试时我注意到响应比触发新 ajax 调用的 SetTimeout 慢,因此页面快速建立运行连接,这可能是因为我的开发服务器有点慢。要解决此问题,您不应该如此频繁地更新,每 5 秒一次就必须这样做。
我猜 asp.net 计时器已经阻止了这种行为:它会在另一个 ajax 调用完成时停止。此行为会导致您遇到问题,按钮回发会阻止计时器更新。
关于c# - Ajax 计时器在处理另一个请求时不轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6895431/