我有这个函数,我试图调用计时器事件作为单独的线程,但当我单击页面中的任何按钮或在asp.net页面中做任何事情时,计时器会停止一秒钟。
请帮助如何在不影响页面中另一个控件的情况下运行它,因为计时器应该每秒钟运行一次,它不应该在ui中停止。
Thread obj = new Thread(new ThreadStart(timer));
obj.Start();
obj.IsBackground = true;
protected void timer()
{
Timer1.Interval = 1000;
Timer1.Tick += new EventHandler<EventArgs>(Timer1_Tick);
Timer1.Enabled = true;
}
public void TimerProc(object state)
{
fromTime = DateTime.Parse(FromTimeTextBox1.Text);
tillTime = DateTime.Parse(TillTimeTextBox1.Text);
DateTime currDateTime = System.DateTime.Now;
TimeSpan interval = tillTime - currDateTime;
if (tillTime <= currDateTime)
{
ExamOverPanel1.Visible = true;
QuestionPanel.Visible = false;
ListBox2.Visible = false;
StatusPanel1.Visible = false;
VisitLaterLabel.Visible = false;
}
else
{
minLabel.Text = string.Format("{0:00}:{1:00}:{2:00}", (int)interval.TotalHours, interval.Minutes, interval.Seconds);
}
}
发布于 2013-03-07 17:23:07
我发现的最好的方法是使用Javascript来显示时间。并在后台运行C#计时器,这将不会更新UI。
<script type="text/javascript">
var serverDateTime = new Date('<%= DateTime.Now.ToString() %>');
// var dif = serverDateTime - new Date();
function updateTime() {
var label = document.getElementById("timelabel");
if (label) {
var time = (new Date());
label.innerHTML = time;
}
}
updateTime();
window.setInterval(updateTime, 1000);
</script>
<script type="text/javascript">
window.onload = WindowLoad;
function WindowLoad(event) {
ActivateCountDown("CountDownPanel", <%=GetTotalSec() %>);
}
//GetTotalSec() is c# function which return some value
</script>
<span id="CountDownPanel"></span> //div to display time
所有其他事情都将在timer1_tick函数上工作,而与UI无关。
发布于 2013-03-05 15:39:41
你的Timer1对象是什么类?
是吗
System.Threading.Timer
或
System.Timers.Timer
或
System.Windows.Forms.Timer
或
System.Web.UI.Timer
?最后两个不是真正合适的计时器,但会到达您的消息队列中……
因此,我建议您检查您的名称空间引用-在您的场景中,我的建议是使用System.Threading.Timer类。
发布于 2013-03-05 16:15:14
我猜您使用的是System.Web.UI.Timer
类,它用于定期更新UpdatePanel
或整个页面。这个计时器不是很精确,因为它完全运行在客户端浏览器上(使用JavaScript window.setTimeout
函数),并向服务器发送ajax请求。如果您想定期在服务器上执行某些操作,您可以使用System.Threading.Timer
对象,该对象在服务器上自己的线程中调用:
public void InitTimer()
{
System.Threading.Timer timer = new System.Threading.Timer(TimerProc);
timer.Change(1000, 1000); // Start after 1 second, repeat every 1 seconds
}
public void TimerProc(object state)
{
// perform the operation
}
但是,如果您希望在服务器上执行某些操作后更新页面,则仍应使用System.Web.UI.Timer
。您也可以将两者混合使用,使用线程计时器来执行高精度的工作,并使用web计时器来更新页面。
有关示例用法,请参阅System.Web.UI.Timer
class的示例部分。
https://stackoverflow.com/questions/15217699
复制相似问题