mercredi 1 avril 2020

ASP.NET Timer do not work. How to call function every X seconds?

I am creating a page in ASP.NET Framework and I need to update text in Label every X seconds. I tried to create new Thread and call Thread.Sleep(), but it do not work, Everything what is written bellow Thread.Sleep do not execute, I do not know why. So I found on internet Timer. I created Timer and it do not call method. If I write it statically to .aspx it works:

 <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();
    }

This works, but I want to change time, so I created it dynamically in C#:

  if (!IsPostBack)
        {
            Timer timer = new Timer();
            timer.Tick += UpdateTimer_Tick;
            timer.Interval = 2000;
            timer.Enabled = true;
        }

But UpdateTimer has never been called. So I tried this and it still do not work:

 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);
    }

I really need this on my website. Please help me. How can I create some routine in ASP.NET? Why I can't use Thread.Sleep in website and why is my timer do not work? Thank you




Aucun commentaire:

Enregistrer un commentaire