无法使计时器事件处理程序工作

时间:2017-09-26 06:41:35

标签: c# asp.net timer

在页面上,我有带定时器的UpdatePanel,工作正常:

<asp:Content ID="content" ContentPlaceHolderID="contentholder" runat="server">
    <asp:ScriptManager runat="server" EnablePartialRendering="true"  ID="ScriptManager"></asp:ScriptManager>
    <asp:Timer ID="Timer" runat="server" Interval="10000" ></asp:Timer>
    <asp:UpdatePanel ID="MainUpdatePanel" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer" EventName="Tick" />
        </Triggers>
        <ContentTemplate>
<!-- some content, including repeaters... -->
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

我无法在代码中使用事件处理程序。

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        Timer.Tick += Timer_Tick;
    }
}

private void Timer_Tick(object sender, EventArgs e)
{
_someFlag = true;
}

我可以在调试期间看到Timer.Tick +=发生得很好,但_someFlag永远不会更改其值,_someFlag = true;永远不会发生,尽管页面本身正确更新。我错过了什么?

2 个答案:

答案 0 :(得分:1)

您必须向计时器添加OnTick="Timer_Tick"属性:

<asp:Timer runat="server" id="Timer1" Interval="10000" OnTick="Timer_Tick"></asp:Timer>

从Page_Load中删除以下代码:

Timer.Tick += Timer_Tick;

答案 1 :(得分:1)

将“计时器”放入“更新面板”中“内容模板”标签用于处理触发事件