asp.net c#中用主线程并行处理Timer Tick事件
本文关键字:并行处理 Timer Tick 事件 线程 net asp | 更新日期: 2023-09-27 18:02:09
我有这个函数,我试图调用定时器事件作为单独的线程,但是当我单击页面中的任何按钮或在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);
}
}
你的Timer1对象是什么类?
它是System.Threading.Timer
或
System.Timers.Timer
或
System.Windows.Forms.Timer
或
System.Web.UI.Timer
?后两个不是真正合适的计时器,但会到达消息队列....
所以我建议你检查你的命名空间引用——我的建议是在你的场景中使用System.Threading.Timer类。
我猜您正在使用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
类的示例部分获取示例用法
我发现最好的方法是使用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
无论UI如何,所有其他东西都将在timer1_tick函数上工作。