Skip to main content
 首页 » 编程设计

c#之计时器不会重置为 30 分钟之每次我返回此页面时,计时器仍在运行

2024年02月20日14lonelyxmas

<分区>

Possible Duplicate:
Does anyone knows how to fix this?My Timer won't reset to 30mins whenever I go back to the web page

这是我的代码,希望有人能帮助我,谢谢

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
        Timer1.Enabled = true; 
        if (Session["CountdownTimer"] == null ) 
        { 
            Session["CountdownTimer"] = new CountDownTimer(TimeSpan.Parse("00:30:00")); 
            (Session["CountdownTimer"] as CountDownTimer).Start(); 
        } 
    } 
} 
 
protected void Timer1_Tick(object sender, EventArgs e) 
{ 
    if (Session["CountdownTimer"] != null) 
    { 
        if (Label1.Text != "00:00:00") 
        { 
            Label1.Text = (Session["CountdownTimer"] as CountDownTimer).TimeLeft.ToString(); 
            Session["time"] = Label1.Text; 
        } 
        else if((Session["CountdownTimer"] as CountDownTimer).TimeLeft.Seconds <= 0) 
        { 
            (Session["CountdownTimer"] as CountDownTimer).Stop(); 
            Timer1.Enabled = false; 
            Response.Redirect("timer.aspx"); 
        } 
    } 
} 
 
public class CountDownTimer 
{ 
    public TimeSpan TimeLeft; 
    System.Threading.Thread thread; 
    public CountDownTimer(TimeSpan original) 
    { 
        this.TimeLeft = original; 
    } 
    public void Start() 
    { 
        // Start a background thread to count down time 
        thread = new System.Threading.Thread(() => 
        { 
            while (true) 
            { 
                System.Threading.Thread.Sleep(1000); 
                TimeLeft = TimeLeft.Subtract(TimeSpan.Parse("00:00:01")); 
 
            } 
        }); 
        thread.Start(); 
    } 
 
    public void Stop() 
    { 
        // Start a background thread to count down time 
        thread = new System.Threading.Thread(() => 
        { 
            while (true) 
            { 
                System.Threading.Thread.Sleep(1000); 
                TimeLeft = (TimeSpan.Parse("00:00:00")); 
 
            } 
        }); 
        thread.Abort(); 
    } 
}