c# - System.Timers.Timer 不工作编辑 [在 asp.net web 表单中]

标签 c# asp.net system.timers.timer

我正在用这段代码尝试 Timer 类:-

protected void Page_Load(object sender, EventArgs e)
{
    System.Timers.Timer tm = new System.Timers.Timer();
    tm.Elapsed += new System.Timers.ElapsedEventHandler(tm_Elapsed);
    tm.Interval = 1000;
    tm.Start();
}

void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    int lbl = Convert.ToInt32(Label1.Text);
    Label1.Text = (lbl+1).ToString();
}

最初,Label1.Text 为“1”。

但是当我运行应用程序时,标签的文本显示 1 并且没有增加。

最佳答案

正如在其他答案中已经提到的,System.Timers.Timer 是在非 GUI 线程上触发的。这将不允许您访问 GUI 元素并会引发跨线程异常。您可以使用 MethodInvoker 访问 tm_Elapsed 事件中的 GUI 元素。由于您在 Forms 中拥有 Timer 并且想要访问 GUI 元素,因此其他 Timer 类最适合您,即 System.Windows.Forms.Timer .

Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.

protected void Page_Load(object sender, EventArgs e)
{         
     System.Windows.Forms.Timer tm = new System.Windows.Forms.Timer();
     tm.Tick += tm_Tick;
     tm.Interval = 1000;
     tm.Start();
}

void tm_Tick(object sender, EventArgs e)
{
     int lbl = Convert.ToInt32(label1.Text);
     label1.Text = (lbl + 1).ToString();
}

编辑 根据 OP 的评论,他是在网页中执行此操作,而不是像加载事件名称所暗示的那样赢得表单。

如果你不需要服务器的任何东西,你可以使用javascript。如果你想更新 html 控件并需要从服务器进行,​​那么你可以使用 asp:Timer

HTML (.aspx)

  <form id="form1" runat="server">             
        <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 id="Label1" runat="server" Text="1" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>

代码隐藏

protected void UpdateTimer_Tick(object sender, EventArgs e)
{
    Label1.Text = int.Parse(Label1.Text) + 1;
}

关于c# - System.Timers.Timer 不工作编辑 [在 asp.net web 表单中],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30093975/

相关文章:

javascript - 从 Base-64 字符串转换为图像时出现异常

c# - 缓存键导致错误 "Negating the minimum value of a twos complement number is invalid."

c# - 在 C# 中将计时器与 fileSystemWatcher 一起使用

c# - 添加单元测试项目时同名文件或文件夹已存在

C# Parallel.ForEach XslCompiledTransform 与 Saxon 9.7.0.6 HE

c# - 使用 XmlReader.Create(uri) 防止或处理超时

asp.net - 自定义404页未针对缺少的ASPX页执行-IIS 7,5

c# 使用 System.Timers 时取消任务

server - Blazor 服务器端计时器正在运行

c# - 线程池 - 限制对某些方法的调用