【发布时间】:2020-07-13 04:00:00
【问题描述】:
我正在 ASP.NET Framework 中创建一个页面,我需要每 X 秒更新一次 Label 中的文本。我尝试创建新的Thread 并调用Thread.Sleep(),但它不起作用,下面写的所有内容 Thread.Sleep 不执行,我不知道为什么。所以我在互联网计时器上找到了。我创建了 Timer,它不调用方法。如果我将它静态写入 .aspx 它可以工作:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000" ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
这可行,但我想更改时间,所以我在 C# 中动态创建它:
if (!IsPostBack)
{
Timer timer = new Timer();
timer.Tick += UpdateTimer_Tick;
timer.Interval = 2000;
timer.Enabled = true;
}
但是UpdateTimer 从未被调用过。所以我尝试了这个,它仍然不起作用:
protected override void OnInit(EventArgs e)
{
if (!IsPostBack)
{
Timer timeoutTimer = new Timer();
timeoutTimer.ID = "timeouttimer";
timeoutTimer.Interval = 10000;
timeoutTimer.Tick += new EventHandler<EventArgs>(UpdarteTimer_Tick);
UpdatePanel timerUpdatePanel = new UpdatePanel();
timerUpdatePanel.ContentTemplateContainer.Controls.Add(timeoutTimer);
ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(timeoutTimer);
this.Page.Form.Controls.Add(timerUpdatePanel);
}
base.OnInit(e);
}
我的网站上真的需要这个。请帮我。如何在 ASP.NET 中创建一些例程?为什么我不能在网站中使用 Thread.Sleep 以及为什么我的计时器不起作用?谢谢
【问题讨论】:
-
你有没有考虑过做这个客户端(在 JS 中)?
-
@SalahAkbari 谢谢,但它不起作用,方法在页面启动时只调用了一次
-
@mjwills 我不懂JS
-
我强烈建议花一些时间学习它。