【发布时间】:2015-06-11 15:43:07
【问题描述】:
我需要在主 UI 线程之外的另一个线程中运行倒数计时器。因此我不能使用DispatcherTimer,因为它只存在于主线程中。因此,我需要对 System.Timers.Timer 的帮助 - 我找不到任何关于如何在网络上创建倒数计时器的好例子..
这是我目前得到的:
Private void CountdownThread()
{
// Calculate the total running time
int runningTime = time.Sum(x => Convert.ToInt32(x));
// Convert to seconds
int totalRunningTime = runningTime * 60;
// New timer
System.Timers.Timer t = new System.Timers.Timer(1000);
t.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) => totalRunningTime--;
// Update the label in the GUI
lblRunning.Dispatcher.BeginInvoke((Action)(() => {lblRunning.Content = totalRunningTime.ToString(@"hh\:mm\:ss");}));
}
标签lblRunning 显示倒计时值。
编辑:问题是我不知道如何在单独的线程中制作倒数计时器并从该线程更新标签!
【问题讨论】:
-
你说不能用主线程,为什么不能呢?听起来您想使用计时器来更新 UI,那么为什么不直接使用
DispatcherTimer呢?这几乎就是它的用途! -
@charles_mager 由于应用程序的设计,我不能使用
DispatcherTimer- 这不是我的决定:-( -
问题是为什么你不能使用它。您的应用程序的设计如何阻止您使用它?毕竟,它正是您应该使用的工具。
-
据我了解,当您更新变量 totalRunningTime 时,您希望 Web 控件(标签)不断更新。您每秒触发一个 Timer 并减少变量,然后更新标签。当前代码是否有任何问题,因为我看到您在 CountDownThread 方法中执行所有操作
-
不会使用像 javascript 这样的客户端脚本来更新 Web 控件上的计时器的更好解决方案。检查以下链接:codeproject.com/Tips/429419/…codeproject.com/Questions/260124/Countdown-timer-in-asp-netforums.asp.net/t/1085601.aspx
标签: c# multithreading timer