1

我有一个页面,当某些操作出错时,我想启动计时器,等待 30 秒,停止计时器并重试操作。每次计时器启动时,我都需要通过更改某些标签的文本来通知用户。

我该怎么做?

4

3 回答 3

4

如果我理解正确,我认为您应该改用客户端(javascript)计时器。您不能为此使用服务器端计时器。

当您检测到错误条件时,您会相应地更新标签并将其显示给用户。同时,您调用一个客户端计时器,该计时器将在 30 秒后回发。

例如,将以下计时器代码放到您的页面上:

  <script>
    function StartTimer()
    {
      setTimeout('DoPostBack()', 30000); // call DoPostBack in 30 seconds
    }
    function DoPostBack()
    {
      __doPostBack(); // invoke the postback
    }
  </script>

如果出现错误情况,您必须确保将启动客户端计时器:

if (error.Code == tooManyClientsErrorCode)
{
  // add some javascript that will call StartTimer() on the client
  ClientScript.RegisterClientScriptBlock(this.GetType(), "timer", "StartTimer();", true);
  //...
}

我希望这会有所帮助(代码未经测试,因为我现在没有可用的 Visual Studio)。

更新:

要“模拟”按钮单击,您必须将按钮的客户端 ID 传递给 __doPostBack() 方法,例如:

function DoPostBack()
{
  var buttonClientId = '<%= myButton.ClientID %>';
  __doPostBack(buttonClientId, ''); // simulate a button click
}

有关其他一些可能性,请参阅以下问题/答案:

于 2009-01-03T15:46:12.247 回答
1

从客户端强制回发您可以直接调用 __doPostBack 方法

它需要两个参数,EVENTTARGET 和 EVENTARGUMENT;由于您是在正常的 asp.net 周期之外进行此调用,因此您需要在页面加载事件(或 init,您的选择)上检查 IsPostBack - 如果它是回发,那么您将需要查看这两个参数作为表单元素 (Request.Form["__EVENTTARGET"])。检查它们的值以查看回发是来自您的呼叫还是其他控件之一,如果这些值与您从客户端传入的值匹配,则对标签测试进行更改

于 2009-01-03T15:07:15.150 回答
0

有两种方法可以做到这一点,第一种方法,如果您需要在同一线程上调用其他函数会更好一些。将 ScriptManager 和 Timer 添加到 aspx 页面,您可以从工具箱中删除或直接输入代码。ScriptManager 必须在 asp:Timer 之前声明。OnTick 在每个间隔后触发。

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:Timer ID="Timer1" runat="server" Interval="4000" OnTick="Timer1_Tick">
    </asp:Timer>

在后面的代码中(在本例中为 c#):

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("tick tock");
    }

如果您需要在同一线程上触发函数,则第二种方法效果不佳。您可以使用 C# 在 ASP.net 中创建一个计时器,以下代码每 2 秒触发一次该函数。在 (.cs) 文件后面的代码中:

    // timer variable
    private static System.Timers.Timer aTimer;

    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;
    }

然后以这种格式制作您要调用的函数:

//Doesn't need to be static if calling other non static functions

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }

样本输出:

输出

于 2018-12-20T15:35:26.100 回答